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, { section: "projects" });
  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 goalId = url.searchParams.get("goalId");
  const health = url.searchParams.get("health");
  const approvalStatus = url.searchParams.get("approvalStatus");

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

  if (auth.workspaceTeamId) {
    if (goalId && health && approvalStatus) {
      const { rows } = await sql`
        SELECT * FROM projects
        WHERE team_id = ${auth.workspaceTeamId}
          AND goal_id = ${goalId}
          AND health = ${health}
          AND approval_status = ${approvalStatus}
        ORDER BY created_at DESC
        LIMIT ${limit}
      `;
      projects = rows;
    } else if (goalId && health) {
      const { rows } = await sql`
        SELECT * FROM projects
        WHERE team_id = ${auth.workspaceTeamId}
          AND goal_id = ${goalId}
          AND health = ${health}
        ORDER BY created_at DESC
        LIMIT ${limit}
      `;
      projects = rows;
    } else if (goalId && approvalStatus) {
      const { rows } = await sql`
        SELECT * FROM projects
        WHERE team_id = ${auth.workspaceTeamId}
          AND goal_id = ${goalId}
          AND approval_status = ${approvalStatus}
        ORDER BY created_at DESC
        LIMIT ${limit}
      `;
      projects = rows;
    } else if (health && approvalStatus) {
      const { rows } = await sql`
        SELECT * FROM projects
        WHERE team_id = ${auth.workspaceTeamId}
          AND health = ${health}
          AND approval_status = ${approvalStatus}
        ORDER BY created_at DESC
        LIMIT ${limit}
      `;
      projects = rows;
    } else if (goalId) {
      const { rows } = await sql`
        SELECT * FROM projects
        WHERE team_id = ${auth.workspaceTeamId}
          AND goal_id = ${goalId}
        ORDER BY created_at DESC
        LIMIT ${limit}
      `;
      projects = rows;
    } else if (health) {
      const { rows } = await sql`
        SELECT * FROM projects
        WHERE team_id = ${auth.workspaceTeamId}
          AND health = ${health}
        ORDER BY created_at DESC
        LIMIT ${limit}
      `;
      projects = rows;
    } else if (approvalStatus) {
      const { rows } = await sql`
        SELECT * FROM projects
        WHERE team_id = ${auth.workspaceTeamId}
          AND approval_status = ${approvalStatus}
        ORDER BY created_at DESC
        LIMIT ${limit}
      `;
      projects = rows;
    } else {
      const { rows } = await sql`
        SELECT * FROM projects
        WHERE team_id = ${auth.workspaceTeamId}
        ORDER BY created_at DESC
        LIMIT ${limit}
      `;
      projects = rows;
    }
  } else {
    if (goalId && health && approvalStatus) {
      const { rows } = await sql`
        SELECT * FROM projects
        WHERE team_id IS NULL
          AND user_id = ${auth.workspaceUserId}
          AND goal_id = ${goalId}
          AND health = ${health}
          AND approval_status = ${approvalStatus}
        ORDER BY created_at DESC
        LIMIT ${limit}
      `;
      projects = rows;
    } else if (goalId && health) {
      const { rows } = await sql`
        SELECT * FROM projects
        WHERE team_id IS NULL
          AND user_id = ${auth.workspaceUserId}
          AND goal_id = ${goalId}
          AND health = ${health}
        ORDER BY created_at DESC
        LIMIT ${limit}
      `;
      projects = rows;
    } else if (goalId && approvalStatus) {
      const { rows } = await sql`
        SELECT * FROM projects
        WHERE team_id IS NULL
          AND user_id = ${auth.workspaceUserId}
          AND goal_id = ${goalId}
          AND approval_status = ${approvalStatus}
        ORDER BY created_at DESC
        LIMIT ${limit}
      `;
      projects = rows;
    } else if (health && approvalStatus) {
      const { rows } = await sql`
        SELECT * FROM projects
        WHERE team_id IS NULL
          AND user_id = ${auth.workspaceUserId}
          AND health = ${health}
          AND approval_status = ${approvalStatus}
        ORDER BY created_at DESC
        LIMIT ${limit}
      `;
      projects = rows;
    } else if (goalId) {
      const { rows } = await sql`
        SELECT * FROM projects
        WHERE team_id IS NULL
          AND user_id = ${auth.workspaceUserId}
          AND goal_id = ${goalId}
        ORDER BY created_at DESC
        LIMIT ${limit}
      `;
      projects = rows;
    } else if (health) {
      const { rows } = await sql`
        SELECT * FROM projects
        WHERE team_id IS NULL
          AND user_id = ${auth.workspaceUserId}
          AND health = ${health}
        ORDER BY created_at DESC
        LIMIT ${limit}
      `;
      projects = rows;
    } else if (approvalStatus) {
      const { rows } = await sql`
        SELECT * FROM projects
        WHERE team_id IS NULL
          AND user_id = ${auth.workspaceUserId}
          AND approval_status = ${approvalStatus}
        ORDER BY created_at DESC
        LIMIT ${limit}
      `;
      projects = rows;
    } else {
      const { rows } = await sql`
        SELECT * FROM projects
        WHERE team_id IS NULL
          AND user_id = ${auth.workspaceUserId}
        ORDER BY created_at DESC
        LIMIT ${limit}
      `;
      projects = rows;
    }
  }

  return NextResponse.json({ projects });
}

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

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

  const name = String(body.name).trim();
  const color = typeof body.color === "string" && body.color ? body.color : "#6366f1";
  const icon = typeof body.icon === "string" && body.icon ? body.icon : "📁";
  const description = typeof body.description === "string" ? body.description : "";
  const goal = typeof body.goal === "string" ? body.goal : "";
  const goal_id = typeof body.goal_id === "string" ? body.goal_id : null;
  const health =
    body.health === "at_risk" || body.health === "stuck" || body.health === "on_track"
      ? body.health
      : "on_track";

  let data: Record<string, unknown>;
  try {
    const { rows } = await sql`
      INSERT INTO projects (user_id, team_id, name, color, icon, description, goal, goal_id, health)
      VALUES (
        ${auth.workspaceUserId},
        ${auth.workspaceTeamId},
        ${name},
        ${color},
        ${icon},
        ${description},
        ${goal},
        ${goal_id},
        ${health}
      )
      RETURNING *
    `;
    data = rows[0];
  } catch (error) {
    const msg = error instanceof Error ? error.message : "Project could not be created";
    return NextResponse.json({ error: msg }, { status: 400 });
  }

  await logProjectActivity(auth.admin, {
    userId: auth.workspaceUserId,
    projectId: data.id as string,
    entityType: "project",
    entityId: data.id as string,
    action: "project_created",
    title: data.name as string,
  });
  await logTeamAudit(auth.admin, {
    teamId: auth.workspaceTeamId,
    actorId: auth.workspaceUserId,
    action: "project_created",
    entityType: "project",
    entityId: data.id as string,
    title: data.name as string,
  });
  await emitWorkspaceWebhookEvent({
    userId: auth.workspaceUserId,
    teamId: auth.workspaceTeamId,
    actorId: auth.workspaceUserId,
    eventType: "project.created",
    data: {
      project: data,
      source: "developer_api",
    },
  });

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