import { logApiError } from "@/lib/api/security";
import { NextResponse } from "next/server";
import { canManageWorkspace } from "@/lib/developers/auth";
import {
  parseAutomationActionType,
  parseAutomationScheduleFrequency,
  parseAutomationTriggerEvent,
  parseAutomationTriggerMode,
  sanitizeAutomationSteps,
  sanitizeAutomationActionConfig,
  sanitizeAutomationConditions,
  sanitizeScheduleDayOfWeek,
  sanitizeScheduleTime,
  sanitizeScheduleTimezone,
  validateAutomationSteps,
} from "@/lib/automations/validation";
import { sql } from "@/lib/db/postgres";
import { createRouteClient } from "@/lib/supabase/route";

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

    const url = new URL(req.url);
    const teamId = url.searchParams.get("teamId");
    const manageable = await canManageWorkspace(user.id, teamId);
    if (!manageable) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

    const [{ rows: rules }, { rows: runs }] = await Promise.all([
      teamId
        ? sql`SELECT * FROM automation_rules WHERE team_id = ${teamId} ORDER BY created_at DESC`
        : sql`SELECT * FROM automation_rules WHERE team_id IS NULL AND user_id = ${user.id} ORDER BY created_at DESC`,
      teamId
        ? sql`SELECT * FROM automation_runs WHERE team_id = ${teamId} ORDER BY created_at DESC LIMIT 40`
        : sql`SELECT * FROM automation_runs WHERE team_id IS NULL AND user_id = ${user.id} ORDER BY created_at DESC LIMIT 40`,
    ]);

    return NextResponse.json({ rules, runs });
  } catch (error) {
    logApiError("Automations GET error", error);
    return NextResponse.json({ error: "Failed to load automations" }, { status: 500 });
  }
}

export async function POST(req: Request) {
  try {
    const supabase = await createRouteClient();
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

    const body = await req.json();
    const teamId = typeof body.teamId === "string" && body.teamId ? body.teamId : null;
    const manageable = await canManageWorkspace(user.id, teamId);
    if (!manageable) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

    const triggerMode = parseAutomationTriggerMode(body.triggerMode) || "event";
    const triggerEvent =
      triggerMode === "schedule"
        ? "schedule.triggered"
        : parseAutomationTriggerEvent(body.triggerEvent);
    const actionType = parseAutomationActionType(body.actionType);
    const name = typeof body.name === "string" ? body.name.trim() : "";
    const description = typeof body.description === "string" ? body.description.trim() : "";

    if (!name) return NextResponse.json({ error: "Automation name is required" }, { status: 400 });
    if (triggerMode === "event" && !triggerEvent) {
      return NextResponse.json({ error: "Choose a valid trigger event" }, { status: 400 });
    }

    const scheduleFrequency = triggerMode === "schedule" ? parseAutomationScheduleFrequency(body.scheduleFrequency) : null;
    const scheduleTime = triggerMode === "schedule" ? sanitizeScheduleTime(body.scheduleTime) : null;
    const scheduleDayOfWeek = triggerMode === "schedule" ? sanitizeScheduleDayOfWeek(body.scheduleDayOfWeek) : null;
    const scheduleTimezone = triggerMode === "schedule" ? sanitizeScheduleTimezone(body.scheduleTimezone) : null;

    if (triggerMode === "schedule") {
      if (!scheduleFrequency || !scheduleTime || !scheduleTimezone) {
        return NextResponse.json({ error: "Daily or weekly schedules need frequency, time, and timezone." }, { status: 400 });
      }
      if (scheduleFrequency === "weekly" && scheduleDayOfWeek === null) {
        return NextResponse.json({ error: "Weekly schedules need a day of week." }, { status: 400 });
      }
    }

    if (!actionType && !Array.isArray(body.steps)) {
      return NextResponse.json({ error: "Choose a valid automation action" }, { status: 400 });
    }

    const steps = sanitizeAutomationSteps(body.steps);
    const fallbackStep = actionType ? [{ id: "step_1", action_type: actionType, action_config: sanitizeAutomationActionConfig(actionType, body.actionConfig) }] : [];
    const nextSteps = steps.length > 0 ? steps : fallbackStep;
    const configError = validateAutomationSteps(nextSteps);
    if (configError || nextSteps.length === 0) {
      return NextResponse.json({ error: configError }, { status: 400 });
    }

    const conditions = sanitizeAutomationConditions(body.conditions);
    const { rows } = await sql`
      INSERT INTO automation_rules (
        user_id, team_id, name, description, trigger_mode, trigger_event,
        schedule_frequency, schedule_time, schedule_day_of_week, schedule_timezone,
        conditions, action_type, action_config, steps, is_active
      ) VALUES (
        ${user.id}, ${teamId}, ${name}, ${description}, ${triggerMode}, ${triggerEvent},
        ${scheduleFrequency}, ${scheduleTime}, ${scheduleDayOfWeek}, ${scheduleTimezone},
        ${JSON.stringify(conditions)}, ${nextSteps[0].action_type}, ${JSON.stringify(nextSteps[0].action_config)},
        ${JSON.stringify(nextSteps)}, ${body.isActive !== false}
      )
      RETURNING *
    `;

    return NextResponse.json({ rule: rows[0] });
  } catch (error) {
    logApiError("Automations POST error", error);
    return NextResponse.json({ error: "Failed to create automation" }, { status: 500 });
  }
}
