import { http, HttpResponse } from "msw";

import { mockDb } from "../db";
import { userIdFromAuthHeader } from "./auth";

const apiBase = "*/api/v1";

function unauthenticated() {
  return HttpResponse.json(
    { errors: [{ code: "unauthenticated", message: "Non authentifié" }] },
    { status: 401 },
  );
}

/** Données dashboard simulées — calibrées sur le wireframe 4.1. */
const SAMPLE_KPIS = {
  rubisCount: 184,
  rubisThisMonth: 124,
  hoursLiberatedThisMonth: 1240, // minutes
  encaisseCents: 1_432_000,
  encaisseDeltaCents: 280_000,
  dsoDays: 38,
  dsoDeltaDays: -6,
  factureToRelance: 8,
  factureInRelance: 11,
  factureNewToday: 3,
  miseEnDemeurePending: 2,
  monthlyGoalProgress: 80,
  percentile: 15,
};

const SAMPLE_ACTIVITY = [
  {
    id: "evt_1",
    kind: "relance_sent",
    at: todayAt(11, 14),
    label: "Relance J+3 envoyée à <b>Atelier Durand</b>",
  },
  {
    id: "evt_2",
    kind: "invoice_paid",
    at: todayAt(10, 2),
    label: "Facture <b>F-2026-0035</b> marquée encaissée",
  },
  {
    id: "evt_3",
    kind: "invoice_imported",
    at: todayAt(9, 48),
    label: "<b>3 factures</b> importées et OCRisées",
  },
  {
    id: "evt_4",
    kind: "warning_drafted",
    at: todayAt(9, 30),
    label: "Brouillon mise en demeure prêt — <b>Cabinet Rousseau</b>",
  },
];

const SAMPLE_LATE_PAYERS = [
  { clientId: "cli_rousseau", name: "Cabinet Rousseau", lateInvoicesCount: 2 },
  { clientId: "cli_durand", name: "Atelier Durand", lateInvoicesCount: 2 },
  { clientId: "cli_lemoine", name: "Garage Lemoine", lateInvoicesCount: 1 },
];

function todayAt(hours: number, minutes: number): string {
  const d = new Date();
  d.setHours(hours, minutes, 0, 0);
  return d.toISOString();
}

export const dashboardHandlers = [
  // GET /api/v1/dashboard/kpis
  http.get(`${apiBase}/dashboard/kpis`, ({ request }) => {
    const userId = userIdFromAuthHeader(request.headers.get("authorization"));
    if (!userId) return unauthenticated();

    // L'utilisateur démo a accès aux KPIs simulés. Les autres (signups frais)
    // démarrent à zéro pour donner un sentiment de "monde vierge".
    const user = mockDb.findUserById(userId);
    if (user?.email === "demo@rubis.fr") {
      return HttpResponse.json({ data: SAMPLE_KPIS });
    }
    return HttpResponse.json({
      data: {
        rubisCount: 0,
        rubisThisMonth: 0,
        hoursLiberatedThisMonth: 0,
        encaisseCents: 0,
        encaisseDeltaCents: 0,
        dsoDays: 0,
        dsoDeltaDays: 0,
        factureToRelance: 0,
        factureInRelance: 0,
        factureNewToday: 0,
        miseEnDemeurePending: 0,
        monthlyGoalProgress: 0,
        percentile: undefined,
      },
    });
  }),

  // GET /api/v1/dashboard/activity
  http.get(`${apiBase}/dashboard/activity`, ({ request }) => {
    const userId = userIdFromAuthHeader(request.headers.get("authorization"));
    if (!userId) return unauthenticated();
    const user = mockDb.findUserById(userId);
    return HttpResponse.json({
      data: user?.email === "demo@rubis.fr" ? SAMPLE_ACTIVITY : [],
    });
  }),

  // GET /api/v1/dashboard/top-late
  http.get(`${apiBase}/dashboard/top-late`, ({ request }) => {
    const userId = userIdFromAuthHeader(request.headers.get("authorization"));
    if (!userId) return unauthenticated();
    const user = mockDb.findUserById(userId);
    return HttpResponse.json({
      data: user?.email === "demo@rubis.fr" ? SAMPLE_LATE_PAYERS : [],
    });
  }),
];
