import { NextRequest, NextResponse } from "next/server";
import { createClient } from "@/lib/supabase/server";
import { logger } from "@/lib/logger";
import { checkRateLimit, getClientIP, createRateLimitResponse } from "@/lib/rate-limit";
import { withCSRFProtection } from "@/lib/csrf";

const RATE_LIMIT = 30;
const WINDOW_MS = 15 * 60 * 1000;

/**
 * POST /api/match/reject
 * 
 * Reject a match and optionally notify the worker.
 * Called when a contractor swipes left / passes on a worker.
 * 
 * Body: { matchId: string, reason?: string }
 */
const handler = async (request: NextRequest) => {
  try {
    const clientIP = getClientIP(request);
    const rateLimit = await checkRateLimit(`reject:${clientIP}`, RATE_LIMIT, WINDOW_MS);
    if (!rateLimit.allowed) {
      const retryAfter = Math.ceil((rateLimit.resetTime - Date.now()) / 1000);
      return createRateLimitResponse(clientIP, retryAfter);
    }

    const supabase = await createClient();
    const { data: { user } } = await supabase.auth.getUser();

    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { matchId, reason } = await request.json();

    if (!matchId) {
      return NextResponse.json({ error: "matchId required" }, { status: 400 });
    }

    // Verify contractor owns this match's job
    const { data: match, error: matchError } = await supabase
      .from("matches")
      .select(`
        id, status, worker_id, contractor_action,
        jobs!inner(title, company_id, companies!inner(profile_id))
      `)
      .eq("id", matchId)
      .single();

    if (matchError || !match) {
      return NextResponse.json({ error: "Match not found" }, { status: 404 });
    }

    const jobs = match.jobs as unknown as {
      title: string;
      company_id: string;
      companies: { profile_id: string };
    };

    if (jobs.companies.profile_id !== user.id) {
      return NextResponse.json({ error: "Not your match" }, { status: 403 });
    }

    if (match.status === "hired") {
      return NextResponse.json({ error: "Cannot reject a hired worker" }, { status: 400 });
    }

    // Update match
    const { error: updateError } = await supabase
      .from("matches")
      .update({
        contractor_action: "rejected",
        status: "rejected",
      })
      .eq("id", matchId);

    if (updateError) {
      logger.error("Failed to reject match:", updateError);
      return NextResponse.json({ error: "Failed to reject" }, { status: 500 });
    }

    // Create gentle notification for the worker
    const { error: notifError } = await supabase
      .from("notifications")
      .insert({
        profile_id: match.worker_id,
        type: "system",
        title: "Job Update",
        body: `The position "${jobs.title}" has been filled. Keep your profile updated — new opportunities are posted daily!`,
        data: { matchId, jobTitle: jobs.title },
      });

    if (notifError) {
      logger.error("Failed to create rejection notification:", notifError);
    }

    return NextResponse.json({ success: true });
  } catch (error) {
    logger.error("Match reject error:", error);
    return NextResponse.json({ error: "Internal error" }, { status: 500 });
  }
};

export const POST = withCSRFProtection(handler);
