/**
 * API client for Seal operations
 */
import { api } from '$lib/api';

export interface Seal {
	id: number;
	seal: string;
	company_id: number;
	tenant_id: number;
}

export interface SealListResponse {
	items: Seal[];
	total: number;
	page: number;
	page_size: number;
	pages: number;
}

export interface SealCreateRequest {
	seal: string;
}

export interface SealUpdateRequest {
	seal?: string;
}

/**
 * Get all seals with pagination and filters
 */
export async function getSeals(
	companyId: number,
	filters?: {
		page?: number;
		page_size?: number;
		seal?: string;
	}
): Promise<{ data: SealListResponse; status: number }> {
	const params = new URLSearchParams();
	params.append('company_id', companyId.toString());
	
	if (filters?.page) params.append('page', filters.page.toString());
	if (filters?.page_size) params.append('page_size', filters.page_size.toString());
	if (filters?.seal) params.append('seal', filters.seal);

	const response = await api.get(`/v1/a76/seals/?${params.toString()}`);

	return response;
}

/**
 * Get a single seal by ID
 */
export async function getSeal(
	id: number,
	companyId: number
): Promise<{ data: Seal; status: number }> {
	const response = await api.get(`/v1/a76/seals/${id}/?company_id=${companyId}`);
	return response;
}

/**
 * Create a new seal
 */
export async function createSeal(
	data: SealCreateRequest,
	companyId: number
): Promise<{ data: Seal; status: number }> {
	const response = await api.post(`/v1/a76/seals/?company_id=${companyId}`, data);
	return response;
}

/**
 * Update an existing seal
 */
export async function updateSeal(
	id: number,
	data: SealUpdateRequest,
	companyId: number
): Promise<{ data: Seal; status: number }> {
	const response = await api.put(`/v1/a76/seals/${id}/?company_id=${companyId}`, data);
	return response;
}

/**
 * Delete a seal
 */
export async function deleteSeal(
	id: number,
	companyId: number
): Promise<{ data: any; status: number }> {
	const response = await api.delete(`/v1/a76/seals/${id}?company_id=${companyId}`);
	return response as any;
}

export const sealsApi = {
    list: (companyId: number, options: Record<string, any> = {}) => {
        const { page = 1, page_size = 50, seal } = options;
        return getSeals(companyId, { page: Number(page), page_size: Number(page_size), seal: seal as string });
    },
    get: (id: number, companyId: number) => getSeal(id, companyId),
    create: (data: SealCreateRequest, companyId: number) => createSeal(data, companyId),
    update: (id: number, data: SealUpdateRequest, companyId: number) => updateSeal(id, data, companyId),
    delete: (id: number, companyId: number) => deleteSeal(id, companyId)
};
