/** Service for business-related API calls */
import { supabase } from '@/supabase'
import type { Business } from '@/types'

const SELECT_FIELDS = 'id, name, address, phone, image_url, social_media, category, latitude, longitude, area, description, website, schedule, whatsapp, instagram, facebook, gallery_images, updated_at'

export const businessService = {
    /** Helper to upload file to supabase storage */
    async uploadImage(file: File): Promise<string> {
        const fileExt = file.name.split('.').pop()
        const fileName = `${Math.random()}-${Date.now()}.${fileExt}`
        const filePath = `businesses/${fileName}`

        const { error } = await supabase.storage.from('uploads').upload(filePath, file)
        if (error) throw new Error(error.message)

        const { data } = supabase.storage.from('uploads').getPublicUrl(filePath)
        return data.publicUrl
    },

    /** Get all businesses */
    async getAllBusinesses(): Promise<Business[]> {
        const { data, error } = await supabase.from('businesses').select(SELECT_FIELDS)
        if (error) throw new Error(error.message)
        return data as Business[]
    },

    /** Get a single business by ID */
    async getBusiness(id: string): Promise<Business> {
        const { data, error } = await supabase.from('businesses').select(SELECT_FIELDS).eq('id', id).single()
        if (error) throw new Error(error.message)
        return data as Business
    },

    /** Parse FormData into a payload object, handling gallery_images JSON */
    _parseFormData(businessData: FormData): { payload: any; fileUpload: File | null } {
        const payload: any = {}
        let fileUpload: File | null = null

        businessData.forEach((value, key) => {
            if ((key === 'file' || key === 'image') && value instanceof File) {
                fileUpload = value
            } else if (key === 'gallery_images' && typeof value === 'string') {
                // Comes as JSON string from the form
                try { payload[key] = JSON.parse(value) } catch { /* ignore */ }
            } else if (value !== 'null' && value !== '' && key !== 'file' && key !== 'image') {
                payload[key] = value
            }
        })

        return { payload, fileUpload }
    },

    /** Create a new business */
    async createBusiness(businessData: FormData): Promise<Business> {
        const { payload, fileUpload } = this._parseFormData(businessData)

        if (fileUpload) {
            payload.image_url = await this.uploadImage(fileUpload)
        }

        const { data, error } = await supabase.from('businesses').insert([payload]).select(SELECT_FIELDS).single()
        if (error) throw new Error(error.message)
        return data as Business
    },

    /** Update an existing business */
    async updateBusiness(id: string, businessData: FormData): Promise<Business> {
        const { payload, fileUpload } = this._parseFormData(businessData)

        if (fileUpload) {
            payload.image_url = await this.uploadImage(fileUpload)
        }

        const { data, error } = await supabase.from('businesses').update(payload).eq('id', id).select(SELECT_FIELDS).single()
        if (error) throw new Error(error.message)
        return data as Business
    },

    /** Delete a business */
    async deleteBusiness(id: string): Promise<void> {
        const { error } = await supabase.from('businesses').delete().eq('id', id)
        if (error) throw new Error(error.message)
    },
}
