import { useRuntimeConfig } from "#app";
import type { FetchResponse } from "ofetch";
import { workpulseApiRaw } from "~/utils/workpulse-api-fetch";
import { normalizeWorkpulseApiBase } from "~/utils/workpulse-api-base";
import { readWorkpulseAccessToken } from "~/utils/workpulse-session-user";
import { useAuth } from "./useAuth";

type ApiEnvelope<T> = {
  ok: boolean;
  data?: T;
  error?: { code?: string; message?: string };
};

export type OrgDivisionRow = {
  code: string;
  label: string;
  reportCount: number;
};

export type OrgByDivisionData = {
  period: string;
  divisions: OrgDivisionRow[];
};

export type OrgDivisionReporter = {
  userId: number;
  name: string;
  email: string;
  isActive: boolean;
  reportCount: number;
};

export type OrgReportersByDivisionData = {
  period: string;
  division: string;
  reporters: OrgDivisionReporter[];
};

/** Satu baris dari `GET /analytics/org/reports-by-reporter` (drill-down). */
export type OrgReportListRow = {
  id: number;
  title: string;
  status: string;
  reportDate?: string;
  updatedAt: string;
};

export type OrgReportsByReporterData = {
  period: string;
  division: string;
  userId: number;
  reports: OrgReportListRow[];
};

function apiBase(): string {
  return normalizeWorkpulseApiBase(String(useRuntimeConfig().public.workpulseApiBase || ""));
}

function bearerHeaders(): { Authorization: string } | undefined {
  const { accessToken } = useAuth();
  const t = accessToken.value || readWorkpulseAccessToken();
  if (!t) return undefined;
  return { Authorization: `Bearer ${t}` };
}

async function parseEnvelope<T>(raw: FetchResponse<unknown>): Promise<{
  ok: boolean;
  status: number;
  data?: T;
  message?: string;
}> {
  const status = raw.status;
  let body = raw._data as ApiEnvelope<T> | string | undefined;
  if (typeof body === "string") {
    try {
      body = JSON.parse(body) as ApiEnvelope<T>;
    } catch {
      body = undefined;
    }
  }
  if (!body) return { ok: false, status, message: `HTTP ${status}` };
  if (!body.ok) {
    return {
      ok: false,
      status,
      message: body.error?.message || body.error?.code || `HTTP ${status}`
    };
  }
  return { ok: true, status, data: body.data as T };
}

/** Hanya untuk **superadmin** — memakai grup `/api/v1/analytics/org`. */
export function useWorkpulseOrgTeamMonitoring() {
  const getByDivision = async (period: string) => {
    const b = apiBase();
    if (!b) return { ok: false as const, status: 0, message: "Layanan belum siap." };
    const qs = new URLSearchParams({ period });
    const raw = await workpulseApiRaw(`${b}/api/v1/analytics/org/by-division?${qs}`, {
      method: "GET",
      headers: bearerHeaders(),
      credentials: "include",
      ignoreResponseError: true
    });
    return parseEnvelope<OrgByDivisionData>(raw);
  };

  const getReportersByDivision = async (division: string, period: string) => {
    const b = apiBase();
    if (!b) return { ok: false as const, status: 0, message: "Layanan belum siap." };
    const qs = new URLSearchParams({ period, division });
    const raw = await workpulseApiRaw(`${b}/api/v1/analytics/org/reporters-by-division?${qs}`, {
      method: "GET",
      headers: bearerHeaders(),
      credentials: "include",
      ignoreResponseError: true
    });
    return parseEnvelope<OrgReportersByDivisionData>(raw);
  };

  const getReportsByReporter = async (userId: number, division: string, period: string) => {
    const b = apiBase();
    if (!b) return { ok: false as const, status: 0, message: "Layanan belum siap." };
    const qs = new URLSearchParams({ period, division, userId: String(userId) });
    const raw = await workpulseApiRaw(`${b}/api/v1/analytics/org/reports-by-reporter?${qs}`, {
      method: "GET",
      headers: bearerHeaders(),
      credentials: "include",
      ignoreResponseError: true
    });
    return parseEnvelope<OrgReportsByReporterData>(raw);
  };

  return { getByDivision, getReportersByDivision, getReportsByReporter };
}
