import client from './client';
import type { PaginatedResponse } from './types';

export interface NumberingRuleInfo {
  id: string;
  name: string;
  code: string;
  prefix: string;
  date_format?: string;
  seq_length: number;
  seq_start: number;
  seq_current: number;
  separator: string;
  reset_cycle: string;
  last_reset_date?: string;
  version: number;
}

export interface CreateNumberingRuleRequest {
  name: string;
  code: string;
  prefix?: string;
  date_format?: string;
  seq_length?: number;
  seq_start?: number;
  separator?: string;
  reset_cycle?: string;
}

export interface UpdateNumberingRuleRequest {
  name?: string;
  prefix?: string;
  date_format?: string;
  seq_length?: number;
  separator?: string;
  reset_cycle?: string;
  version: number;
}

export async function listNumberingRules(page = 1, pageSize = 20) {
  const { data } = await client.get<{ success: boolean; data: PaginatedResponse<NumberingRuleInfo> }>(
    '/config/numbering-rules',
    { params: { page, page_size: pageSize } },
  );
  return data.data;
}

export async function createNumberingRule(req: CreateNumberingRuleRequest) {
  const { data } = await client.post<{ success: boolean; data: NumberingRuleInfo }>(
    '/config/numbering-rules',
    req,
  );
  return data.data;
}

export async function updateNumberingRule(id: string, req: UpdateNumberingRuleRequest) {
  const { data } = await client.put<{ success: boolean; data: NumberingRuleInfo }>(
    `/config/numbering-rules/${id}`,
    req,
  );
  return data.data;
}

export async function generateNumber(id: string) {
  const { data } = await client.post<{ success: boolean; data: { number: string } }>(
    `/config/numbering-rules/${id}/generate`,
  );
  return data.data;
}

export async function deleteNumberingRule(id: string, version: number) {
  await client.delete(`/config/numbering-rules/${id}`, { data: { version } });
}
