import { ApiError, request } from './client';
import type { components } from './generated/v1';

// The list endpoint (GET /api/v1/watermarks) is picker-grade (id + name) and is already
// provided by pickers.ts as getWatermarks(). This module adds the by-id read (full model)
// and the mutations. Image upload is handled by artwork.ts (uploadArtwork(file,'watermark')).

export type WatermarkDetail = components['schemas']['WatermarkFullResponseModel'];
export type CreateWatermarkRequest = components['schemas']['CreateWatermarkRequest'];
export type UpdateWatermarkRequest = components['schemas']['UpdateWatermarkRequest'];

export function getWatermark(id: number): Promise<WatermarkDetail> {
  return request<WatermarkDetail>(`/api/v1/watermarks/${id}`);
}

// Identifies THE default logo-driven preset. imageSource alone is not enough once a second
// ChannelLogo preset exists (the design invites creating one for per-channel geometry), and
// getWatermarks() sorts by name — so prefer the seeded name, then fall back deterministically.
export function findLogoBugWatermark<
  T extends { id: number; imageSource: components['schemas']['ChannelWatermarkImageSource']; name: null | string }
>(watermarks: T[]): T | null {
  const logoDriven = watermarks.filter((watermark) => watermark.imageSource === 'ChannelLogo');
  return logoDriven.find((watermark) => watermark.name === 'Channel Bug') ?? logoDriven[0] ?? null;
}

export function createWatermark(body: CreateWatermarkRequest): Promise<WatermarkDetail> {
  return request<WatermarkDetail>('/api/v1/watermarks', { body, method: 'POST' });
}

export function updateWatermark(id: number, body: UpdateWatermarkRequest): Promise<WatermarkDetail> {
  return request<WatermarkDetail>(`/api/v1/watermarks/${id}`, { body, method: 'PUT' });
}

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

// Preview URL for a custom watermark image. The serve route sniffs the content type from the
// stored file and no longer honors a client-supplied `?contentType=` (issue #283 — that reflection
// was the stored-XSS sink), so the URL is just the path.
export function watermarkImageUrl(path: string): string {
  return `/artwork/watermarks/${path}`;
}

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

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

  return fallback;
}
