"use server";

export type SendEmailPayload = {
    recipient: string;
    subject: string;
    body: string;
};

export type ApiResponse<T> = {
    success?: boolean;
    message?: string;
    data?: T;
};

export type EmailRequest = {
    id: number;
    recipient: string;
    subject: string;
    body: string;
    sentAt: string | null;
    status: "PENDING" | "SENT" | "FAILED" | string;
    errorMessage: string | null;
    createdAt: string;
};

export async function sendEmailAction(
    payload: SendEmailPayload
): Promise<ApiResponse<EmailRequest>> {
    const baseUrl = process.env.BACKEND_BASE_URL;
    if (!baseUrl) {
        throw new Error("BACKEND_BASE_URL is not set");
    }

    const res = await fetch(`${baseUrl}/api/email/send`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            // Authorization: `Bearer ${process.env.BACKEND_JWT}`, // if needed
        },
        body: JSON.stringify(payload),
        cache: "no-store",
    });

    const data: ApiResponse<EmailRequest> | null = await res
        .json()
        .catch(() => null);

    if (!res.ok) {
        throw new Error(data?.message ?? `Request failed with ${res.status}`);
    }

    if (!data) {
        throw new Error("Empty response body");
    }

    return data;
}