/**
 * Resume Recurring Template API
 * POST - Resume a paused recurring template
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { getEffectiveOwnerId } from "@/lib/utils/organization-data";
import { withCSRF } from "@/lib/csrf";
import { logger } from "@/lib/logger";
import { getDataSource } from "@/lib/data-source";
import * as recurringService from "@/lib/services/quotation-recurring.service";

const log = logger.scope("RecurringQuotationResumeAPI");

type RouteContext = { params: Promise<{ id: string }> };

export const POST = withCSRF(
  async (request: NextRequest, context: RouteContext) => {
    try {
      const user = await getAuthenticatedUser(request, auth);
      if (!user) {
        return NextResponse.json(
          { success: false, error: "Unauthorized" },
          { status: 401 },
        );
      }

      const effectiveUserId = await getEffectiveOwnerId(user.userId);
      const { id } = await context.params;

      // ── Convex path ──────────────────────────────────────────────
      if (getDataSource("quotations") === "convex") {
        try {
          const { convexMutation } = await import("@/lib/convex-client");

          const template = await convexMutation(
            "quotations/mutations:resumeRecurring",
            { id: id as any, userId: effectiveUserId },
          );

          if (!template) {
            return NextResponse.json(
              { success: false, error: "Template not found or not paused" },
              { status: 404 },
            );
          }

          return NextResponse.json({ success: true, template });
        } catch (error) {
          console.error("[Convex fallback] recurring resume:", error);
        }
      }

      const template = await recurringService.resumeRecurringTemplate(
        effectiveUserId,
        id,
      );
      if (!template) {
        return NextResponse.json(
          { success: false, error: "Template not found or not paused" },
          { status: 404 },
        );
      }

      return NextResponse.json({ success: true, template });
    } catch (error) {
      log.error("Failed to resume recurring template", error);
      return NextResponse.json(
        { success: false, error: "Internal server error" },
        { status: 500 },
      );
    }
  },
);
