export interface EmailRequest {
  id: number;
  recipient: string;
  email: string;
  status: string;
  createdAt: string;
  updatedAt: string;
}

export interface CreateEmailRequestDto {
  email: string;
  status?: string;
}

export interface UpdateEmailRequestDto {
  email?: string;
  status?: string;
}

export async function fetchEmailRequests(): Promise<EmailRequest[]> {
  const response = await fetch("/api/admin/email", { cache: "no-store" });

  if (!response.ok) {
    throw new Error(`Failed to fetch email requests: ${response.statusText}`);
  }

  const data = (await response.json()) as unknown;
  if (Array.isArray(data)) return data as EmailRequest[];

  const wrapped = data as { data?: unknown; content?: unknown };
  if (Array.isArray(wrapped.data)) return wrapped.data as EmailRequest[];
  if (Array.isArray(wrapped.content)) return wrapped.content as EmailRequest[];
  return [];
}

export async function createEmailRequest(
  data: CreateEmailRequestDto
): Promise<EmailRequest> {
  const response = await fetch("/api/admin/email", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  });

  if (!response.ok) {
    throw new Error(`Failed to create email request: ${response.statusText}`);
  }

  return response.json();
}

export async function updateEmailRequest(
  id: number,
  data: UpdateEmailRequestDto
): Promise<EmailRequest> {
  const response = await fetch(`/api/admin/email/${id}`, {
    method: "PUT",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  });

  if (!response.ok) {
    throw new Error(`Failed to update email request: ${response.statusText}`);
  }

  return response.json();
}

export async function deleteEmailRequest(id: number): Promise<void> {
  const response = await fetch(`/api/admin/email/${id}`, {
    method: "DELETE",
  });

  if (!response.ok) {
    throw new Error(`Failed to delete email request: ${response.statusText}`);
  }
}
