import api from "./api.js";

function unwrap(response) {
  const body = response.data;
  if (body?.success === false) {
    throw new Error(body.message || "Request failed");
  }
  return body?.data ?? body;
}

export async function fetchTickets() {
  return unwrap(await api.get("/tickets"));
}

export async function fetchTicket(id) {
  return unwrap(await api.get(`/tickets/${id}`));
}

export async function fetchTicketTypes() {
  return unwrap(await api.get("/tickets/lookups/types"));
}

export async function fetchTicketStatuses() {
  return unwrap(await api.get("/tickets/lookups/statuses"));
}

export async function fetchTicketLogs({ limit = 200, ticketId, statusId } = {}) {
  return unwrap(
    await api.get("/tickets/logs", {
      params: {
        limit,
        ...(ticketId != null && ticketId !== ""
          ? { ticket_id: ticketId }
          : {}),
        ...(statusId != null && statusId !== ""
          ? { status_id: statusId }
          : {}),
      },
    })
  );
}

export async function createTicket(payload) {
  return unwrap(await api.post("/tickets", payload));
}

export async function updateTicket(id, payload) {
  return unwrap(await api.put(`/tickets/${id}`, payload));
}

export async function startTicket(id) {
  return unwrap(await api.put(`/tickets/${id}/start`));
}

export async function closeTicket(id) {
  return unwrap(await api.put(`/tickets/${id}/close`));
}

export async function deleteTicket(id) {
  return unwrap(await api.delete(`/tickets/${id}`));
}
