import { api } from '@/shared/utils/api';
import type { DependencyType } from '@/features/projects/types/project.types';

export interface TicketDependencyTicketRef {
  id: string;
  ticket_number: string;
  subject: string;
  is_done: boolean;
  status?: { name_en: string; is_closed: boolean };
}

export interface TicketDependencyRecord {
  id: string;
  dependency_type: string;
  ticket: TicketDependencyTicketRef | null;
}

export interface TicketDependencySearchHit {
  id: string;
  ticket_number: string;
  subject: string;
  label: string;
  status?: { name_en: string; is_closed: boolean };
}

export interface TicketDependenciesData {
  blocked_by: TicketDependencyRecord[];
  blocking: TicketDependencyRecord[];
  warnings: TicketDependencyRecord[];
}

export async function fetchTicketDependencies(ticketId: string): Promise<TicketDependenciesData> {
  const res = await api.get<{ data: TicketDependenciesData }>(`/tickets/${ticketId}/dependencies`);
  return res.data;
}

export async function searchDependencyTickets(
  ticketId: string,
  query: string,
): Promise<TicketDependencySearchHit[]> {
  const res = await api.get<{ data: TicketDependencySearchHit[] }>(
    `/tickets/${ticketId}/dependencies/search`,
    { params: { q: query } },
  );
  return res.data ?? [];
}

export async function addDependsOnDependency(
  ticketId: string,
  predecessorTicketId: string,
  dependencyType: DependencyType = 'FS',
): Promise<void> {
  await api.post(`/tickets/${ticketId}/dependencies`, {
    source_ticket_id: predecessorTicketId,
    dependency_type: dependencyType,
  });
}

export async function addBlocksDependency(
  ticketId: string,
  blockedTicketId: string,
  dependencyType: DependencyType = 'FS',
): Promise<void> {
  await api.post(`/tickets/${blockedTicketId}/dependencies`, {
    source_ticket_id: ticketId,
    dependency_type: dependencyType,
  });
}

export async function removeTicketDependency(
  ticketId: string,
  dependencyId: string,
): Promise<void> {
  await api.delete(`/tickets/${ticketId}/dependencies/${dependencyId}`);
}
