/**
 * GET /api/water-logs/export
 *
 * Streams the water log as JSON or CSV. Admin-only — checked via
 * `getAdminUser()` + `can_manage_water_log`. Brand comes from the admin
 * session, with Tuxedo fallback for backward compat.
 *
 *   GET /api/water-logs/export?format=csv
 */
import { NextRequest, NextResponse } from "next/server";
import { getAdminUser } from "@/lib/admin-permissions";
import { getWaterEntries } from "@/actions/water-log/admin";
import type { WaterLogReportRow } from "@/lib/water-log-reporting";

const TUXEDO_BRAND_ID = "64294306-5f42-463d-a5e8-2ad6c81a96de";

export async function GET(request: NextRequest) {
  const adminUser = await getAdminUser();
  if (!adminUser) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  if (!adminUser.can_manage_water_log) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  const { searchParams } = new URL(request.url);
  const format = searchParams.get("format") ?? "json";
  const brandId =
    adminUser.brand_id ??
    process.env.TUXEDO_BRAND_ID ??
    TUXEDO_BRAND_ID;

  const raw = await getWaterEntries(brandId, 10000);
  const rows: WaterLogReportRow[] = raw.map((r) => ({
    logged_at: r.logged_at,
    headgate_name: r.headgate_name,
    user_name: r.user_name,
    user_role: "irrigator",
    measurement: r.measurement,
    unit: r.unit,
    notes: r.notes,
    submitted_via: r.submitted_via,
  }));

  if (format === "csv") {
    const headers = [
      "When",
      "Headgate",
      "User",
      "Measurement",
      "Unit",
      "Total Gallons",
      "Method",
      "Notes",
      "Via",
      "Photo URL",
    ];
    const esc = (s: string | null | undefined) =>
      `"${(s ?? "").replace(/"/g, '""')}"`;
    const lines: string[] = [headers.join(",")];
    for (const e of raw) {
      lines.push(
        [
          esc(e.logged_at),
          esc(e.headgate_name),
          esc(e.user_name),
          String(e.measurement),
          esc(e.unit),
          e.total_gallons != null ? String(e.total_gallons) : "",
          esc(e.method),
          esc(e.notes),
          esc(e.submitted_via),
          esc(e.photo_url),
        ].join(","),
      );
    }
    return new NextResponse(lines.join("\n"), {
      headers: {
        "Content-Type": "text/csv; charset=utf-8",
        "Content-Disposition": `attachment; filename="water-log-${new Date().toISOString().slice(0, 10)}.csv"`,
      },
    });
  }

  return NextResponse.json({ rows });
}
