import type { DepartmentKey } from "@/lib/types";
import type { DepartmentKpiPublishResult, WeeklyKpiIngestPayload } from "@/lib/kpis/types";
import { defaultWeekStartForRequest, upsertWeeklyKpiFromPayload } from "@/lib/kpis/persistence";
import { getWeekBounds } from "@/lib/kpis/date";

type PublishSectionInput = {
  department: DepartmentKey;
  sectionKey: string;
  rawSectionLabel: string;
  ownerTeamLabel: string;
  rows: Array<{
    responsibility: string;
    objectiveIndicator?: string;
    quantityQuality?: string;
    compliance?: string;
    dueCommitment?: string;
  }>;
  weekStart?: string;
  source: string;
};

async function publishSection(input: PublishSectionInput): Promise<DepartmentKpiPublishResult> {
  const weekStart = defaultWeekStartForRequest(input.weekStart);
  const { weekEnd } = getWeekBounds(weekStart);
  const payload: WeeklyKpiIngestPayload = {
    weekStart,
    weekEnd,
    source: input.source,
    sections: [
      {
        sectionKey: input.sectionKey,
        rawSectionLabel: input.rawSectionLabel,
        mappedDepartment: input.department,
        ownerTeamLabel: input.ownerTeamLabel,
        rows: input.rows.map((row, index) => ({
          ...row,
          sortOrder: index,
        })),
      },
    ],
  };

  await upsertWeeklyKpiFromPayload(payload);

  return {
    department: input.department,
    weekStart,
    sectionKey: input.sectionKey,
    rowCount: input.rows.length,
    source: input.source,
  };
}

export async function publishMarketingKpis(input: {
  growthPct7d: number;
  engagementPct7d: number;
  activeInitiatives: number;
  syncStatus: string;
  instagramReach7d?: number;
  instagramFollowers?: number;
  weekStart?: string;
}) {
  const instagramReach7d = Math.max(0, Math.round(input.instagramReach7d ?? 0));
  const instagramFollowers = Math.max(0, Math.round(input.instagramFollowers ?? 0));

  return publishSection({
    department: "marketing",
    sectionKey: "marketing-auto-v1",
    rawSectionLabel: "MARKETING (AUTO V1)",
    ownerTeamLabel: "Marketing",
    source: "marketing-dashboard-v1",
    weekStart: input.weekStart,
    rows: [
      {
        responsibility: "Crecimiento seguidores 7d",
        quantityQuality: `${input.growthPct7d.toFixed(1)}%`,
        compliance: `${Math.max(0, Math.min(100, input.growthPct7d + 50)).toFixed(1)}%`,
        dueCommitment: "Seguimiento semanal",
      },
      {
        responsibility: "Engagement 7d",
        quantityQuality: `${input.engagementPct7d.toFixed(1)}%`,
        compliance: `${Math.max(0, Math.min(100, input.engagementPct7d * 10)).toFixed(1)}%`,
        dueCommitment: "Seguimiento semanal",
      },
      {
        responsibility: "Iniciativas activas",
        quantityQuality: String(input.activeInitiatives),
        objectiveIndicator: ">= 3 iniciativas",
        compliance: input.activeInitiatives >= 3 ? "100%" : "60%",
        dueCommitment: `Meta sync: ${input.syncStatus}`,
      },
      {
        responsibility: "Instagram alcance 7d",
        quantityQuality: String(instagramReach7d),
        objectiveIndicator: "Sync diario 06:00",
        compliance: instagramReach7d > 0 ? "100%" : "70%",
      },
      {
        responsibility: "Instagram followers actual",
        quantityQuality: String(instagramFollowers),
        objectiveIndicator: "Seguimiento diario",
        compliance: instagramFollowers > 0 ? "100%" : "70%",
      },
    ],
  });
}

export async function publishHumanCapitalKpis(input: {
  aggregateScore: number;
  churnPct: number;
  medianTenureMonths: number;
  headcount: number;
  weekStart?: string;
}) {
  return publishSection({
    department: "capital_humano",
    sectionKey: "human-capital-auto-v1",
    rawSectionLabel: "CAPITAL HUMANO (AUTO V1)",
    ownerTeamLabel: "Capital Humano",
    source: "human-capital-dashboard-v1",
    weekStart: input.weekStart,
    rows: [
      {
        responsibility: "People KPI agregado",
        quantityQuality: `${input.aggregateScore.toFixed(1)}%`,
        compliance: `${input.aggregateScore.toFixed(1)}%`,
        dueCommitment: "Seguimiento semanal",
      },
      {
        responsibility: "Rotación mensual",
        quantityQuality: `${input.churnPct.toFixed(1)}%`,
        objectiveIndicator: "<= 8%",
        compliance: input.churnPct <= 8 ? "100%" : "70%",
        dueCommitment: "Monitoreo mensual",
      },
      {
        responsibility: "Tenure mediano",
        quantityQuality: `${input.medianTenureMonths.toFixed(1)} meses`,
        objectiveIndicator: ">= 18 meses",
        compliance: input.medianTenureMonths >= 18 ? "100%" : "65%",
      },
      {
        responsibility: "Headcount activo",
        quantityQuality: String(input.headcount),
        objectiveIndicator: "Cobertura de plantilla",
      },
    ],
  });
}

export async function publishOperationsKpis(input: {
  overdueWorkOrders: number;
  pendingApprovals: number;
  plannedUnits: number;
  forecastUnits: number;
  weekStart?: string;
}) {
  const variance = input.plannedUnits - input.forecastUnits;
  return publishSection({
    department: "operaciones",
    sectionKey: "operations-auto-v1",
    rawSectionLabel: "OPERACIONES / MANTENIMIENTO (AUTO V1)",
    ownerTeamLabel: "Operaciones",
    source: "operations-dashboard-v1",
    weekStart: input.weekStart,
    rows: [
      {
        responsibility: "Work orders vencidas",
        quantityQuality: String(input.overdueWorkOrders),
        objectiveIndicator: "<= 3",
        compliance: input.overdueWorkOrders <= 3 ? "100%" : "55%",
        dueCommitment: "Resolver en la semana",
      },
      {
        responsibility: "Aprobaciones pendientes",
        quantityQuality: String(input.pendingApprovals),
        objectiveIndicator: "<= 5",
        compliance: input.pendingApprovals <= 5 ? "100%" : "70%",
      },
      {
        responsibility: "Planeación vs forecast",
        quantityQuality: `Plan ${input.plannedUnits.toFixed(0)} / Forecast ${input.forecastUnits.toFixed(0)}`,
        compliance: `${Math.max(0, 100 - Math.abs(variance)).toFixed(1)}%`,
        dueCommitment: `Variación ${variance.toFixed(0)} unidades`,
      },
    ],
  });
}

export async function publishProjectsKpis(input: {
  activeProjects: number;
  onTimeMilestonesPct: number;
  blockedTasks: number;
  overdueTasks: number;
  weekStart?: string;
}) {
  return publishSection({
    department: "proyectos",
    sectionKey: "projects-auto-v1",
    rawSectionLabel: "PROYECTOS (AUTO V1)",
    ownerTeamLabel: "Proyectos",
    source: "projects-dashboard-v1",
    weekStart: input.weekStart,
    rows: [
      {
        responsibility: "Proyectos activos",
        quantityQuality: String(input.activeProjects),
        objectiveIndicator: ">= 5",
        compliance: input.activeProjects >= 5 ? "100%" : "70%",
      },
      {
        responsibility: "Hitos en tiempo",
        quantityQuality: `${input.onTimeMilestonesPct.toFixed(1)}%`,
        objectiveIndicator: ">= 80%",
        compliance: input.onTimeMilestonesPct >= 80 ? "100%" : "65%",
      },
      {
        responsibility: "Tareas bloqueadas",
        quantityQuality: String(input.blockedTasks),
        objectiveIndicator: "<= 5",
        compliance: input.blockedTasks <= 5 ? "100%" : "60%",
      },
      {
        responsibility: "Tareas vencidas",
        quantityQuality: String(input.overdueTasks),
        objectiveIndicator: "<= 3",
        compliance: input.overdueTasks <= 3 ? "100%" : "55%",
      },
    ],
  });
}
