import type { FetchResponse } from "ofetch";
import { userFacingApiError } from "~/utils/workpulse-api-error";
import { workpulseApiRaw } from "~/utils/workpulse-api-fetch";
import { normalizeWorkpulseApiBase } from "~/utils/workpulse-api-base";
import { readWorkpulseAccessToken } from "~/utils/workpulse-session-user";

type ApiEnvelope<T> = {
  ok: boolean;
  data?: T;
  error?: { code?: string; message?: string };
};

export type ActivityLogItem = {
  id: number;
  userId?: number;
  action: string;
  title: string;
  detail: string;
  meta?: Record<string, unknown> | null;
  ipAddress: string;
  userAgent: string;
  at: string;
  actorName?: string;
  actorEmail?: string;
};

export type ActivityLogData = {
  items: ActivityLogItem[];
  total: number;
  limit: number;
  offset: number;
  hasMore: boolean;
};

type ActivityLogListParams = {
  limit?: number;
  offset?: number;
  view?: "mine" | "team";
};

function apiBase() {
  const cfg = useRuntimeConfig();
  return normalizeWorkpulseApiBase(cfg.public.workpulseApiBase as string | undefined);
}

function bearerHeaders(): Record<string, string> {
  const token = readWorkpulseAccessToken();
  return token ? { Authorization: `Bearer ${token}` } : {};
}

function parseEnvelope<T>(raw: FetchResponse<unknown>): { ok: true; data: T } | { ok: false; status: number; message: string } {
  const status = raw.status ?? 0;
  let body = raw._data;
  if (typeof body === "string" && body.trim()) {
    try {
      body = JSON.parse(body);
    } catch {
      /* keep string */
    }
  }
  const env = body as ApiEnvelope<T> | undefined;
  if (status >= 200 && status < 300 && env?.ok && env.data !== undefined) {
    return { ok: true, data: env.data };
  }
  return {
    ok: false,
    status,
    message: userFacingApiError({
      status,
      code: env?.error?.code,
      message: env?.error?.message,
      fallback: "Gagal memuat log aktivitas."
    })
  };
}

export function useWorkpulseActivityLog() {
  const getActivityLog = async (params: ActivityLogListParams = {}) => {
    const b = apiBase();
    if (!b) return { ok: false as const, status: 0, message: "Layanan belum siap. Coba lagi nanti." };
    const qs = new URLSearchParams();
    if (params.limit != null) qs.set("limit", String(params.limit));
    if (params.offset != null) qs.set("offset", String(params.offset));
    if (params.view === "team") qs.set("view", "team");
    const q = qs.toString();
    const raw = await workpulseApiRaw(`${b}/api/v1/me/activity-log${q ? `?${q}` : ""}`, {
      method: "GET",
      headers: bearerHeaders(),
      credentials: "include",
      ignoreResponseError: true
    });
    return parseEnvelope<ActivityLogData>(raw);
  };

  const clearActivityLog = async (params: { view?: "mine" | "team"; scope?: "all" | "auth" } = {}) => {
    const b = apiBase();
    if (!b) return { ok: false as const, status: 0, message: "Layanan belum siap. Coba lagi nanti." };
    const qs = new URLSearchParams();
    if (params.scope) qs.set("scope", params.scope);
    if (params.view === "team") qs.set("view", "team");
    const q = qs.toString();
    const raw = await workpulseApiRaw(`${b}/api/v1/me/activity-log${q ? `?${q}` : ""}`, {
      method: "DELETE",
      headers: bearerHeaders(),
      credentials: "include",
      ignoreResponseError: true
    });
    return parseEnvelope<{ deleted: number }>(raw);
  };

  return { getActivityLog, clearActivityLog };
}
