import { del, post, request } from '../httpClient.ts';
import {
  leadCreatePayloadSchema,
  leadCreateResponseSchema,
  leadDeleteResponseSchema,
  leadPageSchema,
  leadSchema,
  type Lead,
  type LeadCreatePayload,
  type LeadCreateResponse,
  type LeadDeleteResponse,
  type LeadPageResponse,
} from './types.ts';

export interface ListLeadsParams {
  limit?: number;
  page?: number;
  q?: string;
}

const PUBLIC_LEADS_ENDPOINT = '/api/v1/leads';
const ADMIN_LEADS_ENDPOINT = '/api/v1/admin/leads';

const buildListQuery = (params?: ListLeadsParams) => {
  if (!params) {
    return undefined;
  }

  const { limit, page, q } = params;
  return { limit, page, q };
};

export const leadsApi = {
  async create(payload: LeadCreatePayload): Promise<LeadCreateResponse> {
    const normalized = leadCreatePayloadSchema.parse(payload);
    return post(PUBLIC_LEADS_ENDPOINT, leadCreateResponseSchema, {
      body: normalized,
    });
  },

  async list(params?: ListLeadsParams): Promise<LeadPageResponse> {
    return request(ADMIN_LEADS_ENDPOINT, leadPageSchema, {
      query: buildListQuery(params),
    });
  },

  async get(id: number): Promise<Lead> {
    return request(`${ADMIN_LEADS_ENDPOINT}/${id}`, leadSchema);
  },

  async remove(id: number): Promise<LeadDeleteResponse> {
    return del(`${ADMIN_LEADS_ENDPOINT}/${id}`, leadDeleteResponseSchema);
  },
};
