import { ApiError, request, requestWithMeta, type ResponseWithMeta } from './client';
import type { components } from './generated/v1';
// FillerPreset is exported by ./pickers — import (don't re-export) to avoid a duplicate `export *`
// name in api/index.ts. LanguageCode/getLanguages moved to ./languages (also re-exported via
// api/index.ts) and are no longer defined here — see docs/decisions.md 2026-07-11 (#212).
import type { FillerPreset } from './pickers';

// The schedule item DTO is FLAT (issue #126/#207): every subtype/mutation field is a nullable
// top-level member, and its mutation fields are named 1:1 with ScheduleItemRequest so a loaded
// item maps back to a PUT/POST body by a straight field copy. See docs/decisions.md 2026-07-10.
export type ScheduleItem = components['schemas']['ScheduleItemResponseModel'];
export type ScheduleItemsResponse = components['schemas']['ScheduleItemsResponseModel'];
export type ScheduleItemRequest = components['schemas']['ScheduleItemRequest'];
export type ReplaceScheduleItemsRequest = components['schemas']['ReplaceScheduleItemsRequest'];
export type ProgramSchedule = components['schemas']['ProgramScheduleResponseModel'];
export type CreateScheduleRequest = components['schemas']['CreateScheduleRequest'];
export type UpdateScheduleRequest = components['schemas']['UpdateScheduleRequest'];
export type NamedId = components['schemas']['NamedIdResponseModel'];
export type FillerKind = components['schemas']['FillerKind'];

// ---- Schedule CRUD -------------------------------------------------------

export function getSchedules(): Promise<ProgramSchedule[]> {
  return request<ProgramSchedule[]>('/api/v1/schedules');
}

export function getScheduleById(id: number): Promise<ProgramSchedule> {
  return request<ProgramSchedule>(`/api/v1/schedules/${id}`);
}

export function createSchedule(body: CreateScheduleRequest): Promise<ProgramSchedule> {
  return request<ProgramSchedule>('/api/v1/schedules', { body, method: 'POST' });
}

export function updateSchedule(id: number, body: UpdateScheduleRequest): Promise<ProgramSchedule> {
  return request<ProgramSchedule>(`/api/v1/schedules/${id}`, { body, method: 'PUT' });
}

export function deleteSchedule(id: number): Promise<void> {
  return request<void>(`/api/v1/schedules/${id}`, { method: 'DELETE' });
}

// ---- Schedule items ------------------------------------------------------

export function getScheduleItems(scheduleId: number): Promise<ScheduleItemsResponse> {
  return request<ScheduleItemsResponse>(`/api/v1/schedules/${scheduleId}/items`);
}

/** Load schedule items together with the schedule's concurrency ETag (issue #253). */
export function getScheduleItemsWithMeta(
  scheduleId: number
): Promise<ResponseWithMeta<ScheduleItemsResponse>> {
  return requestWithMeta<ScheduleItemsResponse>(`/api/v1/schedules/${scheduleId}/items`);
}

export function addScheduleItem(scheduleId: number, body: ScheduleItemRequest): Promise<ScheduleItem> {
  return request<ScheduleItem>(`/api/v1/schedules/${scheduleId}/items`, { body, method: 'POST' });
}

// Id-based reconcile (#259): each item's `id` (round-tripped from the GET response by the editor;
// `null` for a new/copied item never persisted) tells the server which existing row to update in place
// vs. insert, so fill-group/shuffle state on an existing row survives a reorder. The editor batches all
// local draft edits into this single call. Pass the last-seen ETag as `If-Match` to reject a stale
// overwrite with 412; the resolved value carries the new ETag for a subsequent save (issue #253). See
// docs/decisions.md. Note: switching an item's playout-mode/subtype can be a delete+insert server-side,
// so the response's ids may differ from what was sent — the editor must re-seed its draft from the PUT
// response (see SchedulesScreen.tsx `save()`), not reuse the ids it submitted.
export function replaceScheduleItems(
  scheduleId: number,
  body: ReplaceScheduleItemsRequest,
  ifMatch?: string | null
): Promise<ResponseWithMeta<ScheduleItem[]>> {
  return requestWithMeta<ScheduleItem[]>(`/api/v1/schedules/${scheduleId}/items`, {
    body,
    method: 'PUT',
    headers: ifMatch ? { 'If-Match': ifMatch } : undefined
  });
}

export function deleteScheduleItem(scheduleId: number, itemId: number): Promise<void> {
  return request<void>(`/api/v1/schedules/${scheduleId}/items/${itemId}`, { method: 'DELETE' });
}

// ---- Pickers -------------------------------------------------------------
// getLanguages lives in ./languages (imported above); re-exported implicitly via api/index.ts.

export function getFillerPresetsByKind(fillerKind: FillerKind): Promise<FillerPreset[]> {
  return request<FillerPreset[]>(`/api/v1/filler-presets?fillerKind=${encodeURIComponent(fillerKind)}`);
}

// The search-backed source pickers (searchTelevisionShows/…/searchMultiCollections) already live in
// ./blocks — the inspector imports them from '../api' directly.

export function messageFromScheduleError(error: unknown, fallback = 'Unable to load schedules'): string {
  if (error instanceof ApiError) {
    return error.detail ?? error.message;
  }

  if (error instanceof Error) {
    return error.message;
  }

  return fallback;
}
