import SupplierController from '@/actions/App/Http/Controllers/SupplierController';
import type { SupplierDraft } from '@/components/SupplierFormFields.vue';
import type { Supplier } from '@/types/models';

export function emptySupplierDraft(): SupplierDraft {
    return {
        name: '',
        address: '',
        city: '',
        zip_code: '',
        province: '',
        vat_code: '',
        tax_code: '',
        email: '',
        phone: '',
        pec: '',
    };
}

export async function createSupplier(
    draft: SupplierDraft,
): Promise<{ supplier: Supplier; errors: null } | { supplier: null; errors: Partial<Record<keyof SupplierDraft, string>> }> {
    const response = await fetch(SupplierController.store().url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            Accept: 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '',
        },
        body: JSON.stringify(draft),
    });

    if (!response.ok || !response.headers.get('content-type')?.includes('application/json')) {
        if (response.status === 422) {
            const body = await response.json();
            const errors = Object.fromEntries(
                Object.entries(body.errors as Record<string, string[]>).map(([key, messages]) => [key, messages[0]]),
            );
            return { supplier: null, errors };
        }

        return { supplier: null, errors: {} };
    }

    return { supplier: await response.json(), errors: null };
}
