import { NextResponse } from "next/server";
import { authenticateDeveloperRequest } from "@/lib/developers/auth";
import { emitWorkspaceWebhookEvent } from "@/lib/developers/webhooks";
import { logProjectActivity } from "@/lib/project-activity";
import { logTeamAudit } from "@/lib/team-audit";
import { sql } from "@/lib/db/postgres";

export async function GET(req: Request) {
  const auth = await authenticateDeveloperRequest(req);
  if (!auth) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const url = new URL(req.url);
  const limit = Math.min(Math.max(Number(url.searchParams.get("limit") || 50), 1), 100);
  const projectId = url.searchParams.get("projectId");
  const status = url.searchParams.get("status");
  const assigneeId = url.searchParams.get("assigneeId");

  let tasks: Record<string, unknown>[];

  if (auth.workspaceTeamId) {
    if (projectId && status && assigneeId) {
      const { rows } = await sql`
        SELECT * FROM tasks
        WHERE team_id = ${auth.workspaceTeamId}
          AND project_id = ${projectId}
          AND status = ${status}
          AND assignee_id = ${assigneeId}
        ORDER BY sort_order, created_at DESC
        LIMIT ${limit}
      `;
      tasks = rows;
    } else if (projectId && status) {
      const { rows } = await sql`
        SELECT * FROM tasks
        WHERE team_id = ${auth.workspaceTeamId}
          AND project_id = ${projectId}
          AND status = ${status}
        ORDER BY sort_order, created_at DESC
        LIMIT ${limit}
      `;
      tasks = rows;
    } else if (projectId && assigneeId) {
      const { rows } = await sql`
        SELECT * FROM tasks
        WHERE team_id = ${auth.workspaceTeamId}
          AND project_id = ${projectId}
          AND assignee_id = ${assigneeId}
        ORDER BY sort_order, created_at DESC
        LIMIT ${limit}
      `;
      tasks = rows;
    } else if (status && assigneeId) {
      const { rows } = await sql`
        SELECT * FROM tasks
        WHERE team_id = ${auth.workspaceTeamId}
          AND status = ${status}
          AND assignee_id = ${assigneeId}
        ORDER BY sort_order, created_at DESC
        LIMIT ${limit}
      `;
      tasks = rows;
    } else if (projectId) {
      const { rows } = await sql`
        SELECT * FROM tasks
        WHERE team_id = ${auth.workspaceTeamId}
          AND project_id = ${projectId}
        ORDER BY sort_order, created_at DESC
        LIMIT ${limit}
      `;
      tasks = rows;
    } else if (status) {
      const { rows } = await sql`
        SELECT * FROM tasks
        WHERE team_id = ${auth.workspaceTeamId}
          AND status = ${status}
        ORDER BY sort_order, created_at DESC
        LIMIT ${limit}
      `;
      tasks = rows;
    } else if (assigneeId) {
      const { rows } = await sql`
        SELECT * FROM tasks
        WHERE team_id = ${auth.workspaceTeamId}
          AND assignee_id = ${assigneeId}
        ORDER BY sort_order, created_at DESC
        LIMIT ${limit}
      `;
      tasks = rows;
    } else {
      const { rows } = await sql`
        SELECT * FROM tasks
        WHERE team_id = ${auth.workspaceTeamId}
        ORDER BY sort_order, created_at DESC
        LIMIT ${limit}
      `;
      tasks = rows;
    }
  } else {
    if (projectId && status && assigneeId) {
      const { rows } = await sql`
        SELECT * FROM tasks
        WHERE team_id IS NULL
          AND user_id = ${auth.workspaceUserId}
          AND project_id = ${projectId}
          AND status = ${status}
          AND assignee_id = ${assigneeId}
        ORDER BY sort_order, created_at DESC
        LIMIT ${limit}
      `;
      tasks = rows;
    } else if (projectId && status) {
      const { rows } = await sql`
        SELECT * FROM tasks
        WHERE team_id IS NULL
          AND user_id = ${auth.workspaceUserId}
          AND project_id = ${projectId}
          AND status = ${status}
        ORDER BY sort_order, created_at DESC
        LIMIT ${limit}
      `;
      tasks = rows;
    } else if (projectId && assigneeId) {
      const { rows } = await sql`
        SELECT * FROM tasks
        WHERE team_id IS NULL
          AND user_id = ${auth.workspaceUserId}
          AND project_id = ${projectId}
          AND assignee_id = ${assigneeId}
        ORDER BY sort_order, created_at DESC
        LIMIT ${limit}
      `;
      tasks = rows;
    } else if (status && assigneeId) {
      const { rows } = await sql`
        SELECT * FROM tasks
        WHERE team_id IS NULL
          AND user_id = ${auth.workspaceUserId}
          AND status = ${status}
          AND assignee_id = ${assigneeId}
        ORDER BY sort_order, created_at DESC
        LIMIT ${limit}
      `;
      tasks = rows;
    } else if (projectId) {
      const { rows } = await sql`
        SELECT * FROM tasks
        WHERE team_id IS NULL
          AND user_id = ${auth.workspaceUserId}
          AND project_id = ${projectId}
        ORDER BY sort_order, created_at DESC
        LIMIT ${limit}
      `;
      tasks = rows;
    } else if (status) {
      const { rows } = await sql`
        SELECT * FROM tasks
        WHERE team_id IS NULL
          AND user_id = ${auth.workspaceUserId}
          AND status = ${status}
        ORDER BY sort_order, created_at DESC
        LIMIT ${limit}
      `;
      tasks = rows;
    } else if (assigneeId) {
      const { rows } = await sql`
        SELECT * FROM tasks
        WHERE team_id IS NULL
          AND user_id = ${auth.workspaceUserId}
          AND assignee_id = ${assigneeId}
        ORDER BY sort_order, created_at DESC
        LIMIT ${limit}
      `;
      tasks = rows;
    } else {
      const { rows } = await sql`
        SELECT * FROM tasks
        WHERE team_id IS NULL
          AND user_id = ${auth.workspaceUserId}
        ORDER BY sort_order, created_at DESC
        LIMIT ${limit}
      `;
      tasks = rows;
    }
  }

  return NextResponse.json({ tasks });
}

export async function POST(req: Request) {
  const auth = await authenticateDeveloperRequest(req, { write: true });
  if (!auth) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const body = await req.json();
  if (!body?.title) {
    return NextResponse.json({ error: "Task title is required" }, { status: 400 });
  }

  const title = String(body.title).trim();
  const description = typeof body.description === "string" ? body.description : null;
  const priority =
    body.priority === "urgent" ||
    body.priority === "high" ||
    body.priority === "medium" ||
    body.priority === "low" ||
    body.priority === "none"
      ? body.priority
      : "none";
  const status =
    body.status === "todo" ||
    body.status === "in_progress" ||
    body.status === "done" ||
    body.status === "cancelled"
      ? body.status
      : "todo";
  const deadline = typeof body.deadline === "string" ? body.deadline : null;
  const project_id = typeof body.project_id === "string" ? body.project_id : null;
  const goal_id = typeof body.goal_id === "string" ? body.goal_id : null;
  const assignee_id = typeof body.assignee_id === "string" ? body.assignee_id : null;
  const reviewer_id = typeof body.reviewer_id === "string" ? body.reviewer_id : null;
  const review_status =
    body.review_status === "pending_review" ||
    body.review_status === "changes_requested" ||
    body.review_status === "approved" ||
    body.review_status === "not_required"
      ? body.review_status
      : "not_required";
  const review_notes = typeof body.review_notes === "string" ? body.review_notes : "";
  const recurrence_pattern =
    body.recurrence_pattern === "daily" ||
    body.recurrence_pattern === "weekly" ||
    body.recurrence_pattern === "monthly" ||
    body.recurrence_pattern === "none"
      ? body.recurrence_pattern
      : "none";
  const recurrence_interval =
    typeof body.recurrence_interval === "number" && body.recurrence_interval > 0
      ? body.recurrence_interval
      : 1;

  let data: Record<string, unknown>;
  try {
    const { rows } = await sql`
      INSERT INTO tasks (
        user_id, team_id, title, description, priority, status,
        deadline, project_id, goal_id, assignee_id, reviewer_id,
        review_status, review_notes, recurrence_pattern, recurrence_interval
      )
      VALUES (
        ${auth.workspaceUserId},
        ${auth.workspaceTeamId},
        ${title},
        ${description},
        ${priority},
        ${status},
        ${deadline},
        ${project_id},
        ${goal_id},
        ${assignee_id},
        ${reviewer_id},
        ${review_status},
        ${review_notes},
        ${recurrence_pattern},
        ${recurrence_interval}
      )
      RETURNING *
    `;
    data = rows[0];
  } catch (error) {
    const msg = error instanceof Error ? error.message : "Task could not be created";
    return NextResponse.json({ error: msg }, { status: 400 });
  }

  await logProjectActivity(auth.admin, {
    userId: auth.workspaceUserId,
    projectId: data.project_id as string | null,
    entityType: "task",
    entityId: data.id as string,
    action: "task_created",
    title: data.title as string,
    details: {
      status: data.status,
      priority: data.priority,
    },
  });
  await logTeamAudit(auth.admin, {
    teamId: auth.workspaceTeamId,
    actorId: auth.workspaceUserId,
    action: "task_created",
    entityType: "task",
    entityId: data.id as string,
    title: data.title as string,
    details: {
      status: data.status,
      priority: data.priority,
    },
  });
  await emitWorkspaceWebhookEvent({
    userId: auth.workspaceUserId,
    teamId: auth.workspaceTeamId,
    actorId: auth.workspaceUserId,
    eventType: "task.created",
    data: {
      task: data,
      source: "developer_api",
    },
  });

  return NextResponse.json({ task: data }, { status: 201 });
}
