import { request } from "./client";
import {
  Contract,
  ContractPayload,
  PaperlessDocument,
  PaperlessSearchResponse,
  UpcomingDeadline
} from "../types";

export interface ContractsQuery {
  skip?: number;
  limit?: number;
}

export async function fetchContracts(query: ContractsQuery = {}): Promise<Contract[]> {
  const params = new URLSearchParams();
  if (query.skip !== undefined) params.set("skip", String(query.skip));
  if (query.limit !== undefined) params.set("limit", String(query.limit));

  const suffix = params.toString() ? `?${params.toString()}` : "";
  const result = await request<unknown>(`/contracts${suffix}`, { method: "GET" });
  if (!Array.isArray(result)) {
    throw new Error("Unexpected response format for contracts");
  }
  return result as Contract[];
}

export async function fetchContract(contractId: number): Promise<Contract> {
  const result = await request<unknown>(`/contracts/${contractId}`, { method: "GET" });
  if (!result || typeof result !== "object") {
    throw new Error("Unexpected response format for contract");
  }
  return result as Contract;
}

export async function createContract(payload: ContractPayload): Promise<Contract> {
  return request<Contract>("/contracts", {
    method: "POST",
    body: payload
  });
}

export async function updateContract(
  contractId: number,
  payload: Partial<ContractPayload>
): Promise<Contract> {
  return request<Contract>(`/contracts/${contractId}`, {
    method: "PUT",
    body: payload
  });
}

export async function removeContract(contractId: number): Promise<void> {
  await request(`/contracts/${contractId}`, { method: "DELETE" });
}

export async function fetchUpcomingDeadlines(days?: number): Promise<UpcomingDeadline[]> {
  const params = new URLSearchParams();
  if (days !== undefined) params.set("days", String(days));
  const suffix = params.toString() ? `?${params.toString()}` : "";
  const result = await request<unknown>(`/reports/upcoming${suffix}`, { method: "GET" });
  if (!Array.isArray(result)) {
    throw new Error("Unexpected response format for deadlines");
  }
  return result as UpcomingDeadline[];
}

export async function fetchPaperlessDocument(
  contractId: number
): Promise<PaperlessDocument | null> {
  try {
    return await request<PaperlessDocument | null>(`/contracts/${contractId}/paperless-document`, {
      method: "GET"
    });
  } catch (error) {
    if ((error as { status?: number }).status === 404) {
      return null;
    }
    throw error;
  }
}

export async function searchPaperlessDocuments(query: string, page = 1): Promise<PaperlessSearchResponse> {
  const params = new URLSearchParams({ q: query, page: String(page) });
  return request<PaperlessSearchResponse>(`/integrations/paperless/search?${params.toString()}`, {
    method: "GET"
  });
}
