import { NextRequest, NextResponse } from "next/server";
import { tripService } from "@/server/services/trip.service";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

/**
 * Cron daily — flip trip yang sudah lewat tanggal selesai dari OPEN/FULL ke
 * COMPLETED. Idempotent: run berulang aman.
 *
 * Trigger via system crontab (lihat [docs/CRON_SETUP.md](../../../docs/CRON_SETUP.md))
 * atau cron service apapun. Header wajib: `Authorization: Bearer ${CRON_SECRET}`.
 *
 * Set env `CRON_SECRET` (random ≥32 char) di hosting. Kalau env tidak di-set,
 * endpoint hard-fail 500 supaya tidak accidentally jalan tanpa proteksi.
 */
export async function GET(req: NextRequest) {
  const secret = process.env.CRON_SECRET;
  if (!secret) {
    console.error("[cron/auto-complete-trips] CRON_SECRET tidak di-set");
    return NextResponse.json(
      { error: "Server misconfigured" },
      { status: 500 }
    );
  }

  const authHeader = req.headers.get("authorization");
  if (authHeader !== `Bearer ${secret}`) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const result = await tripService.autoCompletePastTrips();
    console.log("[cron/auto-complete-trips] selesai", {
      count: result.count,
      ids: result.ids,
    });
    return NextResponse.json({
      ok: true,
      completed: result.count,
      ids: result.ids,
    });
  } catch (err) {
    console.error("[cron/auto-complete-trips] gagal", err);
    return NextResponse.json(
      { error: "Gagal menjalankan auto-complete" },
      { status: 500 }
    );
  }
}
