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";
import type { AutomationRule } from "@/types";

export async function PATCH(req: Request, context: { params: Promise<{ id: string }> }) {
  try {
    const supabase = await createRouteClient();
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

    const { id } = await context.params;
    const { rows } = await sql`SELECT * FROM automation_rules WHERE id = ${id} LIMIT 1`;
    const currentRule = (rows[0] ?? null) as AutomationRule | null;
    if (!currentRule) return NextResponse.json({ error: "Automation not found" }, { status: 404 });

    const manageable = await canManageWorkspace(user.id, currentRule.team_id);
    if (!manageable) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

    const body = await req.json();
    const nextTriggerMode = parseAutomationTriggerMode(body.triggerMode) || currentRule.trigger_mode;
    const nextTriggerEvent =
      nextTriggerMode === "schedule"
        ? "schedule.triggered"
        : parseAutomationTriggerEvent(body.triggerEvent) || currentRule.trigger_event;
    const nextActionType = parseAutomationActionType(body.actionType) || currentRule.action_type;
    const providedSteps = body.steps !== undefined ? sanitizeAutomationSteps(body.steps) : null;
    const nextConditions = body.conditions !== undefined ? sanitizeAutomationConditions(body.conditions) : currentRule.conditions;
    const nextActionConfig =
      body.actionConfig !== undefined || body.actionType !== undefined
        ? sanitizeAutomationActionConfig(nextActionType, body.actionConfig)
        : currentRule.action_config;
    const nextSteps =
      providedSteps && providedSteps.length > 0
        ? providedSteps
        : body.actionType !== undefined || body.actionConfig !== undefined
        ? [{ id: currentRule.steps?.[0]?.id || "step_1", action_type: nextActionType, action_config: nextActionConfig }, ...(Array.isArray(currentRule.steps) ? currentRule.steps.slice(1) : [])]
        : Array.isArray(currentRule.steps) && currentRule.steps.length > 0
        ? currentRule.steps
        : [{ id: "step_1", action_type: currentRule.action_type, action_config: currentRule.action_config }];

    const configError = validateAutomationSteps(nextSteps);
    const scheduleFrequency = nextTriggerMode === "schedule" ? parseAutomationScheduleFrequency(body.scheduleFrequency) || currentRule.schedule_frequency : null;
    const scheduleTime = nextTriggerMode === "schedule" ? sanitizeScheduleTime(body.scheduleTime) || currentRule.schedule_time : null;
    const scheduleDayOfWeek = nextTriggerMode === "schedule" ? (body.scheduleDayOfWeek !== undefined ? sanitizeScheduleDayOfWeek(body.scheduleDayOfWeek) : currentRule.schedule_day_of_week) : null;
    const scheduleTimezone = nextTriggerMode === "schedule" ? sanitizeScheduleTimezone(body.scheduleTimezone) || currentRule.schedule_timezone : null;

    if (configError) return NextResponse.json({ error: configError }, { status: 400 });
    if (nextTriggerMode === "schedule") {
      if (!scheduleFrequency || !scheduleTime || !scheduleTimezone) {
        return NextResponse.json({ error: "Scheduled automations 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 });
      }
    }

    const nextName = typeof body.name === "string" ? (body.name.trim() || currentRule.name) : currentRule.name;
    const nextDescription = typeof body.description === "string" ? body.description.trim() : currentRule.description;
    const nextIsActive = typeof body.isActive === "boolean" ? body.isActive : currentRule.is_active;

    const { rows: updated } = await sql<AutomationRule>`
      UPDATE automation_rules SET
        trigger_mode = ${nextTriggerMode},
        trigger_event = ${nextTriggerEvent},
        schedule_frequency = ${scheduleFrequency},
        schedule_time = ${scheduleTime},
        schedule_day_of_week = ${scheduleDayOfWeek},
        schedule_timezone = ${scheduleTimezone},
        conditions = ${JSON.stringify(nextConditions)},
        action_type = ${nextSteps[0].action_type},
        action_config = ${JSON.stringify(nextSteps[0].action_config)},
        steps = ${JSON.stringify(nextSteps)},
        name = ${nextName},
        description = ${nextDescription},
        is_active = ${nextIsActive}
      WHERE id = ${id}
      RETURNING *
    `;

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

export async function DELETE(_req: Request, context: { params: Promise<{ id: string }> }) {
  try {
    const supabase = await createRouteClient();
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

    const { id } = await context.params;
    const { rows } = await sql<{ id: string; team_id: string | null }>`
      SELECT id, team_id FROM automation_rules WHERE id = ${id} LIMIT 1
    `;
    if (!rows[0]) return NextResponse.json({ error: "Automation not found" }, { status: 404 });

    const manageable = await canManageWorkspace(user.id, rows[0].team_id);
    if (!manageable) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

    await sql`DELETE FROM automation_rules WHERE id = ${id}`;
    return NextResponse.json({ success: true });
  } catch (error) {
    logApiError("Automations DELETE error", error);
    return NextResponse.json({ error: "Failed to delete automation" }, { status: 500 });
  }
}
