import { api } from "./client";

export interface CarBrief {
  id: number;
  plate: string;
  brand: string | null;
  model: string | null;
}

export interface CarContext {
  id: number;
  plate: string;
  brand: string | null;
  model: string | null;
  mileage_starline: number | null;
  driver_id: number | null;
  driver_name: string | null;
}

export interface MechWork {
  id: number;
  name: string;
  category_id: number;
  price: number | string;
  norma_hours: number | string | null;
}

export interface PartSuggestion {
  name: string;
}

export interface PresignResponse {
  photo_uuid: string;
  extension: string;
  content_type: string;
  key: string;
  upload_url: string;
  expires_in: number;
}

export interface CreatePhotoPayload {
  photo_uuid: string;
  extension: string;
  tag: "auto" | "part" | "other";
  sort_order: number;
}

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

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

export interface CreateOilChangePayload {
  enabled: boolean;
  mileage_at_change: number | null;
  next_in_km: number;
  sticker_photo_uuid: string | null;
  sticker_extension: string | null;
}

export interface ExternalCarPayload {
  plate: string;
  make: string | null;
}

export interface CreateRepairPayload {
  car_id?: number;
  external_car?: ExternalCarPayload;
  mileage: number | null;
  works: CreateWorkPayload[];
  parts: CreatePartPayload[];
  photos: CreatePhotoPayload[];
  oil_change: CreateOilChangePayload | null;
  // Работавшие механики (делёж 1/N). Если не передан — backend сидит
  // одного создателя. Порядок = sort_order.
  mechanic_ids?: number[];
}

// ── Ростер механиков (пикер «Механики») ────────────────────────────────────

export interface MechanicRosterItem {
  id: number;
  full_name: string;
}

export async function getMechanicsRoster(): Promise<MechanicRosterItem[]> {
  // prefixUrl = /api/v1/mechanic, эндпоинт под роутером /v1/mechanic/repairs →
  // путь обязан включать сегмент repairs/ (как и остальные вызовы файла).
  return api.get("repairs/mechanics-roster").json<MechanicRosterItem[]>();
}

export interface CreateRepairResponse {
  id: number;
  created_at_iso: string;
  tg_outbox_status: string;
}

export async function searchCars(q: string): Promise<CarBrief[]> {
  const qs = q ? `?q=${encodeURIComponent(q)}` : "";
  return api.get(`cars${qs}`).json<CarBrief[]>();
}

export async function getCarContext(carId: number): Promise<CarContext> {
  return api.get(`cars/${carId}/context`).json<CarContext>();
}

export async function searchWorks(q: string): Promise<MechWork[]> {
  const qs = q ? `?q=${encodeURIComponent(q)}` : "";
  return api.get(`works${qs}`).json<MechWork[]>();
}

export async function suggestParts(q: string): Promise<PartSuggestion[]> {
  return api
    .get(`parts/suggest?q=${encodeURIComponent(q)}`)
    .json<PartSuggestion[]>();
}

export async function presignPhoto(extension: string, photo_uuid?: string): Promise<PresignResponse> {
  return api
    .post("repairs/photos/presign", {
      json: { extension, photo_uuid: photo_uuid ?? null },
    })
    .json<PresignResponse>();
}

/**
 * Залить файл по presigned PUT. ВАЖНО: Content-Type ОБЯЗАН совпадать
 * со значением, которое сервер вшил в подпись (см. У18 / sto_mechanic_form.py).
 */
export async function uploadPhotoToTmp(file: File | Blob, presign: PresignResponse): Promise<void> {
  const res = await fetch(presign.upload_url, {
    method: "PUT",
    headers: { "Content-Type": presign.content_type },
    body: file,
  });
  if (!res.ok) {
    throw new Error(`Photo upload failed: ${res.status} ${res.statusText}`);
  }
}

export async function createRepair(
  payload: CreateRepairPayload,
  idempotencyKey: string,
): Promise<CreateRepairResponse> {
  return api
    .post("repairs", {
      json: payload,
      headers: { "Idempotency-Key": idempotencyKey },
    })
    .json<CreateRepairResponse>();
}
