import { randomUUID } from "node:crypto";
import { getDbPool } from "@/db";

type VehicleType = "light" | "motorcycle" | "heavy";

const vehicleTypes: { value: VehicleType; label: string }[] = [
  { value: "light", label: "Leves" },
  { value: "motorcycle", label: "Motos" },
  { value: "heavy", label: "Pesados" },
];

const standardRules = [
  { code: "CHASSIS_DIVERGENT", name: "Divergência ou possível adulteração do chassi", ruleType: "blocking", points: 100, action: "reject", condition: { type: "finding_contains", values: ["chassi divergente", "chassi adulterado", "identificador divergente"] } },
  { code: "FRAUD_INDICATOR", name: "Indício de fraude estrutural ou documental", ruleType: "blocking", points: 100, action: "reject", condition: { type: "finding_contains", values: ["fraude", "documento adulterado", "veículo clonado"] } },
  { code: "STRUCTURAL_DAMAGE", name: "Avaria estrutural crítica", ruleType: "scoring", points: 70, action: "reject", condition: { type: "finding_contains", values: ["longarina", "estrutura comprometida", "airbag acionado", "incêndio"] } },
  { code: "SEVERE_DAMAGE", name: "Avaria grave identificada", ruleType: "scoring", points: 45, action: "human_review", condition: { type: "finding_contains", values: ["avaria grave", "dano grave", "deformação severa"] } },
  { code: "MODERATE_DAMAGE", name: "Avaria moderada identificada", ruleType: "scoring", points: 25, action: "approve_with_notes", condition: { type: "finding_contains", values: ["avaria moderada", "amassado", "arranhão profundo"] } },
  { code: "LIGHT_DAMAGE", name: "Avaria leve identificada", ruleType: "scoring", points: 10, action: "approve", condition: { type: "finding_contains", values: ["avaria leve", "arranhão superficial", "amassado leve"] } },
  { code: "LOW_CONFIDENCE", name: "Baixa confiança na leitura da IA", ruleType: "retriage", points: 0, action: "retriage", condition: { type: "min_confidence", threshold: 80 } },
  { code: "AI_REQUIRES_HUMAN", name: "IA solicitou conferência humana", ruleType: "routing", points: 0, action: "human_review", condition: { type: "requires_human" } },
  { code: "MANUAL_DAMAGE_LIGHT", name: "Avaria leve confirmada pelo analista", ruleType: "scoring", points: 10, action: "approve", condition: { type: "manual_assessment", values: ["damage_light"] } },
  { code: "MANUAL_DAMAGE_MODERATE", name: "Avaria moderada confirmada pelo analista", ruleType: "scoring", points: 25, action: "approve_with_notes", condition: { type: "manual_assessment", values: ["damage_moderate"] } },
  { code: "MANUAL_DAMAGE_SEVERE", name: "Avaria grave confirmada pelo analista", ruleType: "scoring", points: 45, action: "human_review", condition: { type: "manual_assessment", values: ["damage_severe"] } },
  { code: "MANUAL_DAMAGE_STRUCTURAL", name: "Avaria estrutural/crítica confirmada pelo analista", ruleType: "blocking", points: 70, action: "reject", condition: { type: "manual_assessment", values: ["damage_structural"] } },
  { code: "MANUAL_PLATE_DIVERGENT", name: "Placa divergente confirmada pelo analista", ruleType: "retriage", points: 0, action: "retriage", condition: { type: "manual_assessment", values: ["plate_divergent"] } },
  { code: "MANUAL_CHASSIS_DIVERGENT", name: "Chassi divergente ou adulterado confirmado pelo analista", ruleType: "blocking", points: 100, action: "reject", condition: { type: "manual_assessment", values: ["chassis_divergent"] } },
] as const;

/**
 * Garante que todo cliente tenha um conjunto ativo e utilizável de regras.
 * A operação é idempotente: conjuntos existentes nunca são alterados.
 */
export async function ensureDefaultRuleSets(tenantId: string) {
  const db = getDbPool();
  const created: VehicleType[] = [];

  for (const vehicleType of vehicleTypes) {
    const [activeRows] = await db.execute(
      "SELECT id FROM rule_sets WHERE tenant_id = ? AND vehicle_type = ? AND status = 'active' LIMIT 1",
      [tenantId, vehicleType.value],
    );
    if ((activeRows as unknown[]).length) continue;

    const ruleSetId = randomUUID();
    const connection = await db.getConnection();
    try {
      await connection.beginTransaction();
      const [lockedRows] = await connection.execute(
        "SELECT id FROM rule_sets WHERE tenant_id = ? AND vehicle_type = ? AND status = 'active' LIMIT 1 FOR UPDATE",
        [tenantId, vehicleType.value],
      );
      if ((lockedRows as unknown[]).length) {
        await connection.commit();
        continue;
      }

      const version = "capital-standard-v1";
      await connection.execute(
        "INSERT INTO rule_sets (id, tenant_id, vehicle_type, name, version, status, confidence_threshold, approved_limit, review_limit, rejected_limit) VALUES (?, ?, ?, ?, ?, 'active', 80, 19, 40, 70)",
        [ruleSetId, tenantId, vehicleType.value, `Padrão Autovistoria Veicular - ${vehicleType.label}`, version],
      );
      for (const rule of standardRules) {
        await connection.execute(
          "INSERT INTO rules (id, rule_set_id, code, name, rule_type, points, action, condition_json, is_enabled) VALUES (?, ?, ?, ?, ?, ?, ?, ?, TRUE)",
          [randomUUID(), ruleSetId, rule.code, rule.name, rule.ruleType, rule.points, rule.action, JSON.stringify(rule.condition)],
        );
      }
      await connection.commit();
      created.push(vehicleType.value);
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  }

  return created;
}
