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

export type ChannelTemplate = components['schemas']['ChannelTemplateResponseModel'];
export type CreateChannelTemplateRequest = components['schemas']['CreateChannelTemplateRequest'];

export function getChannelTemplates(): Promise<ChannelTemplate[]> {
  return request<ChannelTemplate[]>('/api/v1/channel-templates');
}

export async function getDefaultChannelTemplate(): Promise<ChannelTemplate | null> {
  try {
    return await request<ChannelTemplate>('/api/v1/channel-templates/default');
  } catch (error) {
    if (error instanceof ApiError && error.status === 404) {
      return null;
    }

    throw error;
  }
}

export function createChannelTemplate(body: CreateChannelTemplateRequest): Promise<ChannelTemplate> {
  return request<ChannelTemplate>('/api/v1/channel-templates', {
    body,
    method: 'POST'
  });
}

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

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

  return fallback;
}
