import client from "./client";

// ── Types ───────────────────────────────────────────────────────────

export interface Worklog {
  id: string;
  entity_type: string;
  entity_id: string;
  user_id: string;
  activity_type: string;
  started_at: string;
  ended_at: string | null;
  duration_seconds: number;
  description: string | null;
  tempo_synced: string | null;
  tempo_worklog_id: string | null;
  integrity_hash: string | null;
  created_at: string;
}

export interface WorklogCreatePayload {
  entity_type: string;
  entity_id: string;
  activity_type: string;
  started_at: string;
  ended_at?: string;
  duration_seconds: number;
  description?: string;
}

// ── API Functions ───────────────────────────────────────────────────

/** Create a manual worklog entry. */
export async function createWorklog(
  payload: WorklogCreatePayload,
): Promise<Worklog> {
  const { data } = await client.post<Worklog>("/worklogs", payload);
  return data;
}

/** List worklogs with optional filters. */
export async function listWorklogs(params?: {
  entity_type?: string;
  entity_id?: string;
  user_id?: string;
}): Promise<Worklog[]> {
  const { data } = await client.get<Worklog[]>("/worklogs", { params });
  return data;
}

/** Get a single worklog. */
export async function getWorklog(worklogId: string): Promise<Worklog> {
  const { data } = await client.get<Worklog>(`/worklogs/${worklogId}`);
  return data;
}

/** List worklogs for a specific test (shorthand). */
export async function listTestWorklogs(testId: string): Promise<Worklog[]> {
  return listWorklogs({ entity_type: "test", entity_id: testId });
}

/** Verify a worklog's integrity hash. */
export async function verifyWorklogIntegrity(
  worklogId: string,
): Promise<{ worklog_id: string; integrity_valid: boolean }> {
  const { data } = await client.get(`/worklogs/${worklogId}/verify`);
  return data;
}
