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 AnalyticsSummary = {
  reportsTotal: number;
  notificationsUnread: number;
};

export type TrendPoint = {
  date: string;
  count: number;
};

export type AnalyticsTrends = {
  reportsByDay: TrendPoint[];
  days?: number;
  align?: string;
};

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 };
}

export function useWorkpulseAnalytics() {
  const getSummary = async () => {
    const b = apiBase();
    if (!b) return { ok: false as const, status: 0, message: "Layanan belum siap." };
    const raw = await workpulseApiRaw(`${b}/api/v1/analytics/summary`, {
      method: "GET",
      headers: bearerHeaders(),
      credentials: "include",
      ignoreResponseError: true
    });
    return parseEnvelope<AnalyticsSummary>(raw);
  };

  const getTrends = async (params: { days?: number; align?: "week" } = {}) => {
    const b = apiBase();
    if (!b) return { ok: false as const, status: 0, message: "Layanan belum siap." };
    const qs = new URLSearchParams();
    if (params.days != null) qs.set("days", String(params.days));
    if (params.align) qs.set("align", params.align);
    const q = qs.toString();
    const raw = await workpulseApiRaw(`${b}/api/v1/analytics/trends${q ? `?${q}` : ""}`, {
      method: "GET",
      headers: bearerHeaders(),
      credentials: "include",
      ignoreResponseError: true
    });
    return parseEnvelope<AnalyticsTrends>(raw);
  };

  return { getSummary, getTrends };
}
