import { api } from "./client";

export interface FeedWorkBrief {
  name: string;
}

export interface FeedItem {
  id: number;
  created_at: string; // ISO
  car_plate: string;
  car_make: string | null;
  car_model: string | null;
  driver_name: string | null;
  mechanic_name: string;
  is_external: boolean;
  works_preview: FeedWorkBrief[];
  works_extra: number;
  works_total: number; // сумма работ без запчастей
  photo_url: string | null;
}

export interface FeedResponse {
  items: FeedItem[];
  next_cursor: string | null;
}

export interface FeedParams {
  limit?: number;
  cursor?: string | null;
}

export async function getRepairsFeed(params: FeedParams = {}): Promise<FeedResponse> {
  const search = new URLSearchParams();
  if (params.limit) search.set("limit", String(params.limit));
  if (params.cursor) search.set("cursor", params.cursor);
  const qs = search.toString();
  return api
    .get(`repairs${qs ? `?${qs}` : ""}`)
    .json<FeedResponse>();
}

export interface RepairsMonthStats {
  total: number;
  count: number;
}

export async function getRepairsMonthStats(): Promise<RepairsMonthStats> {
  return api.get("repairs/stats/month").json<RepairsMonthStats>();
}

// ── Детальная карточка ремонта ─────────────────────────────────────────────

export interface RepairDetailWork {
  id: number;
  work_catalog_id: number;
  name: string;
  price_applied: number;
  manual_override: boolean;
  override_comment: string | null;
}

export interface RepairDetailPart {
  id: number;
  name: string;
  qty: number;
}

export interface RepairDetailPhoto {
  photo_uuid: string;
  thumb_url: string | null;
  orig_url: string | null;
}

export interface RepairDetailOil {
  mileage_at_change: number | null;
  next_in_km: number | null;
  has_sticker: boolean;
  sticker_thumb_url: string | null;
  sticker_orig_url: string | null;
}

export interface RepairDetailMechanic {
  id: number;
  mechanic_id: number;
  name: string;
}

export interface RepairDetailResponse {
  id: number;
  created_at: string;
  car_plate: string | null;
  car_make: string | null;
  car_model: string | null;
  driver_name: string | null;
  mechanic_name: string | null;
  mileage: number | null;
  works: RepairDetailWork[];
  parts: RepairDetailPart[];
  photos: RepairDetailPhoto[];
  oil_change: RepairDetailOil | null;
  total_sum: number;
  // Работавшие механики (делёж 1/N total_sum). Может отсутствовать на
  // старых ответах backend — фронт делает fallback на одного создателя.
  mechanics?: RepairDetailMechanic[];
  edited_in_crm: boolean;
  can_edit: boolean;
  edit_until: string | null;
}

export async function getRepairDetail(id: number): Promise<RepairDetailResponse> {
  return api.get(`repairs/${id}`).json<RepairDetailResponse>();
}

// ── PATCH (правка в 1-часовом окне У49) ────────────────────────────────────

export interface PatchWork {
  work_catalog_id: number;
  price_applied: number;
  manual_override: boolean;
  override_comment: string | null;
}

export interface PatchPart {
  name: string;
  qty: number;
}

export interface PatchOilChange {
  enabled: boolean;
  mileage_at_change: number | null;
  next_in_km: number | null;
}

export interface PatchRepairPayload {
  mileage: number | null;
  works: PatchWork[];
  parts: PatchPart[];
  oil_change: PatchOilChange | null;
  // Работавшие механики. Опционально — если не передан, набор не меняется.
  mechanic_ids?: number[];
}

export async function patchRepair(id: number, body: PatchRepairPayload): Promise<RepairDetailResponse> {
  return api.patch(`repairs/${id}`, { json: body }).json<RepairDetailResponse>();
}
