import { logError } from "@/lib/logger";
import { error as errorResponse, success } from "@/lib/response";
import { SMTP_FROM, transporter } from "@/lib/mailer";
import { CONSOLE_SSO_TTL_MINUTES, consoleSsoLink } from "@/lib/console-sso";
import {
  ExportStorage,
  buildExportObjectPath,
} from "@/lib/storage/export-storage";
import { EXPORT_FILE_TTL_HOURS } from "@/internal/queue/export-file-purge.worker";
import { randomUUID } from "node:crypto";
import {
  sendExportApprovalRequestMail,
  sendExportApprovedMail,
  sendExportRejectedMail,
  sendExportReviewedMail,
} from "@/lib/templates/export-requests";
import {
  ExportRequestsRepository,
  type ConsoleUserRecipient,
  type ExportRequestRow,
  type ExportRequestStatus,
} from "@/internal/repository/admin_console/export_requests";
import type { Context } from "hono";
import type Mail from "nodemailer/lib/mailer";

const ALLOWED_SECTIONS = new Set([
  "campaigns",
  "promoCodes",
  "memberReferrals",
  "reports",
  "bookings",
]);

const MAX_FILE_BYTES = 12 * 1024 * 1024;

const XLSX_MIME =
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

const QUEUE_PATH = "/admin/export-requests";

function repo(c: Context) {
  return new ExportRequestsRepository(c.get("datastore"));
}

function isSuperAdmin(c: Context): boolean {
  return c.get("isAdminConsoleSuperAdmin") === true;
}

function requesterEmail(c: Context): string {
  return String(c.get("adminEmail") ?? "");
}

function xlsxName(filename: string): string {
  return filename.endsWith(".xlsx") ? filename : `${filename}.xlsx`;
}

function workbookAttachment(
  filename: string,
  bytes: Buffer,
): Mail.Options["attachments"] {
  return [{ filename: xlsxName(filename), content: bytes, contentType: XLSX_MIME }];
}

async function resolveWorkbook(row: {
  id: string;
  file_path: string | null;
  file_bytes: Buffer | null;
  file_purged_at: string | null;
}): Promise<Buffer | null> {
  if (row.file_purged_at) return null;
  if (row.file_path) {
    const bytes = await ExportStorage().getWorkbook(row.file_path);
    if (!bytes) {
      logError(
        `Export request ${row.id} points at ${row.file_path}, but no such object exists.`,
      );
    }
    return bytes;
  }
  return row.file_bytes ?? null;
}

function mailSummary(row: ExportRequestRow) {
  return {
    label: row.label,
    requestedBy: row.requested_by,
    requestedAt: row.created_at,
    rowCount: row.row_count,
    fileSize: row.file_size,
    filename: xlsxName(row.filename),
    filtersSummary: row.filters_summary,
  };
}

async function requesterAccount(
  c: Context,
  row: ExportRequestRow,
): Promise<ConsoleUserRecipient | null> {
  try {
    const found = row.requested_by_id
      ? await repo(c).consoleUserById(row.requested_by_id)
      : await repo(c).consoleUserByEmail(row.requested_by);
    if (found) return found;
    return row.requested_by_id
      ? { id: row.requested_by_id, email: row.requested_by, name: row.requested_by }
      : null;
  } catch (err) {
    logError("Could not resolve the requester's console account:", err);
    return null;
  }
}

function describeRequester(
  account: ConsoleUserRecipient | null,
  email: string,
): string {
  const name = account?.name?.trim();
  return name && name.toLowerCase() !== email.toLowerCase()
    ? `${name} (${email})`
    : email;
}

export const createExportRequestHandler = async (c: Context) => {
  try {
    const body = (await c.req.json().catch(() => null)) as {
      section?: string;
      label?: string;
      filename?: string;
      filtersSummary?: string;
      rowCount?: number;
      fileBase64?: string;
    } | null;
    if (!body) return errorResponse(c, "Expected a JSON body", 400);

    const section = String(body.section ?? "");
    if (!ALLOWED_SECTIONS.has(section)) {
      return errorResponse(c, "Unknown export section", 400);
    }
    if (!body.fileBase64) {
      return errorResponse(c, "The generated file is required", 400);
    }

    const email = requesterEmail(c);
    if (!email) {
      return errorResponse(
        c,
        "Your account has no email address, so an export cannot be delivered.",
        400,
      );
    }

    let file: Buffer;
    try {
      file = Buffer.from(body.fileBase64, "base64");
    } catch {
      return errorResponse(c, "The file could not be decoded", 400);
    }
    if (file.length === 0) return errorResponse(c, "The file is empty", 400);
    if (file.length > MAX_FILE_BYTES) {
      return errorResponse(
        c,
        `Export is too large (${file.length} bytes, limit ${MAX_FILE_BYTES}).`,
        413,
      );
    }

    const filename = String(body.filename ?? "export").replace(
      /[^\w.\-]+/g,
      "_",
    );

    const objectPath = buildExportObjectPath(
      randomUUID(),
      xlsxName(filename),
      new Date(),
    );
    await ExportStorage().putWorkbook(objectPath, file);

    let row;
    try {
      row = await repo(c).create({
        requestedBy: email,
        requestedById: String(c.get("consoleUserId") ?? "") || null,
        section,
        label: String(body.label ?? section),
        filename,
        filtersSummary: body.filtersSummary ? String(body.filtersSummary) : null,
        rowCount: Number(body.rowCount ?? 0),
        filePath: objectPath,
        fileSize: file.length,
      });
    } catch (insertErr) {
      await ExportStorage().deleteWorkbook(objectPath);
      throw insertErr;
    }

    void (async () => {
      try {
        const admins = await repo(c).superAdmins();
        if (admins.length === 0) return;

        const requester = await requesterAccount(c, row);
        const summary = {
          ...mailSummary(row),
          requestedBy: describeRequester(requester, email),
        };

        for (const admin of admins) {
          try {
            const reviewLink = await consoleSsoLink(c, {
              userId: admin.id,
              next: QUEUE_PATH,
            });
            const mail = await sendExportApprovalRequestMail(
              {
                ...summary,
                reviewerEmail: admin.email,
                reviewLink,
                ssoMinutes: CONSOLE_SSO_TTL_MINUTES,
              },
              { from: SMTP_FROM, to: admin.email },
            );
            await transporter.sendMail(mail);
          } catch (perAdminErr) {
            logError(
              `Failed notifying super admin ${admin.email} of an export request:`,
              perAdminErr,
            );
          }
        }
      } catch (notifyErr) {
        logError("Export request saved but notifying super admins failed:", notifyErr);
      }
    })();

    return success(c, row, "Export request submitted for approval", 201);
  } catch (err: any) {
    logError("Error in createExportRequestHandler:", err);
    return errorResponse(c, err?.message || "Failed to submit request", 500);
  }
};

export const listExportRequestsHandler = async (c: Context) => {
  try {
    const q = c.req.query();
    const status = q.status as ExportRequestStatus | undefined;
    const limit = Math.min(100, Math.max(1, parseInt(q.limit ?? "25", 10) || 25));
    const offset = Math.max(0, parseInt(q.offset ?? "0", 10) || 0);

    const result = await repo(c).list({
      status:
        status === "pending" || status === "approved" || status === "rejected"
          ? status
          : undefined,
      requestedBy: isSuperAdmin(c) ? undefined : requesterEmail(c),
      limit,
      offset,
    });

    return success(
      c,
      { ...result, canReview: isSuperAdmin(c) },
      "Export requests fetched",
      200,
    );
  } catch (err: any) {
    logError("Error in listExportRequestsHandler:", err);
    return errorResponse(c, err?.message || "Failed to list requests", 500);
  }
};

export const downloadExportRequestFileHandler = async (c: Context) => {
  try {
    const id = c.req.param("id");
    if (!id) return errorResponse(c, "Request id is required", 400);

    const full = await repo(c).getWithFile(id);
    if (!full) return errorResponse(c, "Request not found", 404);

    if (!isSuperAdmin(c)) {
      const email = requesterEmail(c);
      const isOwn =
        Boolean(email) &&
        full.requested_by.toLowerCase() === email.toLowerCase();
      if (!isOwn) {
        return errorResponse(c, "You cannot download this export.", 403);
      }
      if (full.status !== "approved") {
        return errorResponse(
          c,
          "This export hasn't been approved yet, so it can't be downloaded.",
          403,
        );
      }
    }

    const bytes = await resolveWorkbook(full);
    if (!bytes) {
      return errorResponse(
        c,
        full.file_purged_at
          ? `This file was deleted ${EXPORT_FILE_TTL_HOURS} hours after it was emailed. Ask the requester for their copy, or request the export again.`
          : "The file for this request is no longer available.",
        410,
      );
    }

    const filename = xlsxName(full.filename);
    return c.body(new Uint8Array(bytes), 200, {
      "Content-Type": XLSX_MIME,
      "Content-Disposition": `attachment; filename="${filename}"`,
      "Content-Length": String(bytes.length),
      "Cache-Control": "no-store",
    });
  } catch (err: any) {
    logError("Error in downloadExportRequestFileHandler:", err);
    return errorResponse(c, err?.message || "Failed to download the export", 500);
  }
};

function notifySuperAdminsOfReview(
  c: Context,
  args: {
    row: ExportRequestRow;
    requestedBy: string;
    decision: "approved" | "rejected";
    reviewedBy: string;
    note: string | null;
    deliveryStatus: string;
  },
): void {
  void (async () => {
    try {
      const admins = await repo(c).superAdmins();
      if (admins.length === 0) return;

      for (const admin of admins) {
        try {
          const queueLink = await consoleSsoLink(c, {
            userId: admin.id,
            next: QUEUE_PATH,
          });
          const mail = await sendExportReviewedMail(
            {
              ...mailSummary(args.row),
              decision: args.decision,
              reviewedBy: args.reviewedBy,
              reviewedAt: args.row.reviewed_at ?? new Date().toISOString(),
              note: args.note,
              deliveryStatus: args.deliveryStatus,
              queueLink,
              reviewerEmail: admin.email,
              ssoMinutes: CONSOLE_SSO_TTL_MINUTES,
            },
            { from: SMTP_FROM, to: admin.email },
          );
          await transporter.sendMail(mail);
        } catch (perAdminErr) {
          logError(
            `Failed sending the review record to ${admin.email}:`,
            perAdminErr,
          );
        }
      }
    } catch (err) {
      logError("Could not send the export review record to super admins:", err);
    }
  })();
}

export const reviewExportRequestHandler = async (c: Context) => {
  try {
    if (!isSuperAdmin(c)) {
      return errorResponse(
        c,
        "Only a super admin can approve or reject an export.",
        403,
      );
    }
    const id = c.req.param("id");
    if (!id) return errorResponse(c, "Request id is required", 400);

    const body = (await c.req.json().catch(() => null)) as {
      action?: string;
      note?: string;
    } | null;
    const approve = body?.action === "approve";
    if (!approve && body?.action !== "reject") {
      return errorResponse(c, "action must be approve or reject", 400);
    }

    const reviewer = requesterEmail(c) || "super admin";
    const note = body?.note ? String(body.note) : null;

    const reviewed = await repo(c).review({
      id,
      status: approve ? "approved" : "rejected",
      reviewedBy: reviewer,
      note,
    });
    if (!reviewed) {
      return errorResponse(
        c,
        "That request no longer needs review — it may already have been actioned.",
        409,
      );
    }

    const requester = await requesterAccount(c, reviewed);
    const requesterLink = await consoleSsoLink(c, {
      userId: requester?.id,
      next: QUEUE_PATH,
    });
    const reviewedAt = reviewed.reviewed_at ?? new Date().toISOString();
    const requestedBy = describeRequester(requester, reviewed.requested_by);

    if (!approve) {
      try {
        const mail = await sendExportRejectedMail(
          {
            ...mailSummary(reviewed),
            requestedBy,
            reviewedBy: reviewer,
            reviewedAt,
            note,
            queueLink: requesterLink,
            ssoForEmail: requester ? reviewed.requested_by : null,
            ssoMinutes: CONSOLE_SSO_TTL_MINUTES,
          },
          { from: SMTP_FROM, to: reviewed.requested_by },
        );
        await transporter.sendMail(mail);
      } catch (mailErr) {
        logError("Export rejected but notifying the requester failed:", mailErr);
      }

      notifySuperAdminsOfReview(c, {
        row: reviewed,
        requestedBy,
        decision: "rejected",
        reviewedBy: reviewer,
        note,
        deliveryStatus: "No file was sent.",
      });

      return success(c, reviewed, "Export request rejected", 200);
    }

    const full = await repo(c).getWithFile(id);
    if (!full) return errorResponse(c, "Request not found", 404);

    const workbook = await resolveWorkbook(full);
    if (!workbook) {
      const reason = "The stored file could not be found, so nothing was sent.";
      await repo(c).markDelivery(id, reason);
      notifySuperAdminsOfReview(c, {
        row: reviewed,
        requestedBy,
        decision: "approved",
        reviewedBy: reviewer,
        note,
        deliveryStatus: reason,
      });
      return success(
        c,
        { ...reviewed, delivery_error: reason },
        `Approved, but ${reason.toLowerCase()}`,
        200,
      );
    }

    try {
      const mail = await sendExportApprovedMail(
        {
          ...mailSummary(full),
          requestedBy,
          reviewedBy: reviewer,
          reviewedAt,
          note,
          queueLink: requesterLink,
          ssoForEmail: requester ? full.requested_by : null,
          ssoMinutes: CONSOLE_SSO_TTL_MINUTES,
          retentionHours: EXPORT_FILE_TTL_HOURS,
        },
        { from: SMTP_FROM, to: full.requested_by },
        workbookAttachment(full.filename, workbook),
      );
      await transporter.sendMail(mail);
      await repo(c).markDelivery(id, null);
    } catch (mailErr: any) {
      logError("Export approved but email failed:", mailErr);
      await repo(c).markDelivery(id, String(mailErr?.message ?? mailErr));
      notifySuperAdminsOfReview(c, {
        row: reviewed,
        requestedBy,
        decision: "approved",
        reviewedBy: reviewer,
        note,
        deliveryStatus: `Sending the file to ${full.requested_by} failed: ${String(
          mailErr?.message ?? mailErr,
        )}`,
      });
      return success(
        c,
        { ...reviewed, delivery_error: String(mailErr?.message ?? mailErr) },
        "Approved, but sending the email failed. It can be resent.",
        200,
      );
    }

    notifySuperAdminsOfReview(c, {
      row: reviewed,
      requestedBy,
      decision: "approved",
      reviewedBy: reviewer,
      note,
      deliveryStatus: `Emailed to ${full.requested_by}.`,
    });

    return success(c, reviewed, "Export approved and emailed", 200);
  } catch (err: any) {
    logError("Error in reviewExportRequestHandler:", err);
    return errorResponse(c, err?.message || "Failed to review request", 500);
  }
};
