import { NextResponse } from "next/server";
import { getServiceSupabase } from "@/lib/supabase/client";
import { getAuthenticatedUser } from "@/lib/server/auth";

export const runtime = "nodejs";

interface Task {
  id: string;
  title: string;
  description?: string;
  type: "idea" | "task" | "bug" | "research" | "plan";
  status: "open" | "todo" | "blocked" | "in-progress" | "review" | "validate" | "archived" | "canceled" | "done";
  priority: "low" | "medium" | "high" | "urgent";
  projectId: string;
  sprintId?: string;
  createdAt?: string;
  updatedAt?: string;
  createdById?: string;
  createdByName?: string;
  createdByAvatarUrl?: string;
  updatedById?: string;
  updatedByName?: string;
  updatedByAvatarUrl?: string;
  assigneeId?: string;
  assigneeName?: string;
  assigneeEmail?: string;
  assigneeAvatarUrl?: string;
  dueDate?: string;
  comments?: unknown[];
  tags?: string[];
  attachments?: unknown[];
}

// GET - fetch all tasks, projects, and sprints
export async function GET() {
  try {
    const user = await getAuthenticatedUser();
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
    
    const supabase = getServiceSupabase();
    
    const [{ data: projects }, { data: sprints }, { data: tasks }, { data: meta }] = await Promise.all([
      supabase.from("projects").select("*").order("created_at", { ascending: true }),
      supabase.from("sprints").select("*").order("start_date", { ascending: true }),
      supabase.from("tasks").select("*").order("created_at", { ascending: true }),
      supabase.from("meta").select("value").eq("key", "lastUpdated").maybeSingle(),
    ]);
    
    return NextResponse.json({
      projects: projects || [],
      sprints: sprints || [],
      tasks: tasks || [],
      lastUpdated: Number(meta?.value ?? Date.now()),
    });
  } catch (error) {
    console.error(">>> API GET error:", error);
    return NextResponse.json({ error: "Failed to fetch data" }, { status: 500 });
  }
}

// POST - create or update a single task (lightweight)
export async function POST(request: Request) {
  try {
    const user = await getAuthenticatedUser();
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const body = await request.json();
    const { task } = body as { task?: Task };

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

    const supabase = getServiceSupabase();
    const now = new Date().toISOString();

    // Check if task exists
    const { data: existing } = await supabase
      .from("tasks")
      .select("id")
      .eq("id", task.id)
      .maybeSingle();

    const taskData = {
      id: task.id,
      title: task.title,
      description: task.description || null,
      type: task.type || "task",
      status: task.status || "todo",
      priority: task.priority || "medium",
      project_id: task.projectId,
      sprint_id: task.sprintId || null,
      created_at: existing ? undefined : (task.createdAt || now),
      updated_at: now,
      created_by_id: existing ? undefined : (task.createdById || user.id),
      created_by_name: existing ? undefined : (task.createdByName || user.name),
      created_by_avatar_url: existing ? undefined : task.createdByAvatarUrl,
      updated_by_id: user.id,
      updated_by_name: user.name,
      updated_by_avatar_url: user.avatarUrl,
      assignee_id: task.assigneeId || null,
      assignee_name: task.assigneeName || null,
      assignee_email: task.assigneeEmail || null,
      assignee_avatar_url: task.assigneeAvatarUrl || null,
      due_date: task.dueDate || null,
      comments: task.comments || [],
      tags: task.tags || [],
      attachments: task.attachments || [],
    };

    let result;
    if (existing) {
      // Update existing
      const { data, error } = await supabase
        .from("tasks")
        .update(taskData)
        .eq("id", task.id)
        .select()
        .single();
      if (error) throw error;
      result = data;
    } else {
      // Insert new
      const { data, error } = await supabase
        .from("tasks")
        .insert(taskData)
        .select()
        .single();
      if (error) throw error;
      result = data;
    }

    // Update lastUpdated
    await supabase.from("meta").upsert({
      key: "lastUpdated",
      value: String(Date.now()),
      updated_at: now,
    });

    return NextResponse.json({ success: true, task: result });
  } catch (error: unknown) {
    console.error(">>> API POST error:", error);
    const message = error instanceof Error ? error.message : "Failed to save";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}

// DELETE - remove a task
export async function DELETE(request: Request) {
  try {
    const user = await getAuthenticatedUser();
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { id } = (await request.json()) as { id: string };
    
    const supabase = getServiceSupabase();
    const { error } = await supabase.from("tasks").delete().eq("id", id);
    
    if (error) throw error;

    // Update lastUpdated
    await supabase.from("meta").upsert({
      key: "lastUpdated",
      value: String(Date.now()),
      updated_at: new Date().toISOString(),
    });

    return NextResponse.json({ success: true });
  } catch (error: unknown) {
    console.error(">>> API DELETE error:", error);
    const message = error instanceof Error ? error.message : "Failed to delete";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
