/**
 * GET /clean-logs/unscheduled/{report_id}/advice — 予定なしの行の対応アドバイス
 *
 * 仕様の正は `d-watch-api.yaml` の /clean-logs/unscheduled/{report_id}/advice です。
 */
import { NextResponse } from "next/server";
import { parsePathReportId } from "@/lib/api/path-params";
import { adviceResponse } from "@/lib/clean-logs/advice-response";
import { db } from "@/lib/db";
import { logApiError } from "@/lib/logger/api";
import { withRequestId } from "@/lib/logger";
import type { ApiError, ErrorCode } from "@/lib/types";

const ROUTE = "/api/clean-logs/unscheduled/[report_id]/advice";

function errorBody(code: ErrorCode, message: string): ApiError {
  return { error: { code, message, details: null } };
}

function errorResponse(status: number, code: ErrorCode, message: string) {
  return NextResponse.json(errorBody(code, message), { status });
}

export async function GET(
  request: Request,
  { params }: { params: Promise<{ report_id: string }> }
) {
  return withRequestId(request, async () => {
    const { report_id } = await params;
    const parsed = parsePathReportId(report_id);
    if (!parsed.ok) {
      return NextResponse.json(parsed.error, { status: parsed.status });
    }
    const reportId = parsed.query;

    let log;
    try {
      log = await db.unscheduledCleanLog(reportId);
    } catch (e) {
      const body = errorBody("internal_error", "データの取得に失敗しました");
      logApiError({ route: ROUTE, method: "GET", body, status: 500, err: e });
      return NextResponse.json(body, { status: 500 });
    }

    if (!log) {
      return errorResponse(404, "not_found", "指定された清掃ログが見つかりません");
    }

    return adviceResponse(log, { route: ROUTE, logIds: { report_id: reportId } });
  });
}
