import { client } from './client.js'

const DEFAULT_FIELDS = [
    'id',
    'status',
    'title',
    'slug',
    'price',
    'currency',
    'condition',
    'expires_at',
    'date_created',
    'user_created',
    'images.directus_files_id.id',
    'category.id',
    'category.name',
    'category.slug',
    'category.icon',
    'location.id',
    'location.name',
    'location.postal_code',
    'location.country',
    'location.latitude',
    'location.longitude'
]

const DETAIL_FIELDS = [
    'id',
    'status',
    'title',
    'slug',
    'description',
    'price',
    'currency',
    'price_mode',
    'price_type',
    'condition',
    'shipping',
    'shipping_cost',
    'views',
    'expires_at',
    'date_created',
    'user_created',
    'images.directus_files_id.id',
    'category.id',
    'category.name',
    'category.slug',
    'category.translations.*',
    'location.id',
    'location.name',
    'location.postal_code',
    'location.country'
]

export async function getListings(options = {}) {
    const params = {
        fields: options.fields || DEFAULT_FIELDS,
        filter: options.filter || {
            status: { _eq: 'published' },
            _or: [
                { expires_at: { _null: true } },
                { expires_at: { _gt: '$NOW' } }
            ]
        },
        sort: options.sort || ['-date_created'],
        limit: options.limit || 20,
        page: options.page || 1
    }

    if (options.search) {
        params.search = options.search
    }

    const response = await client.get('/items/listings', params)
    return {
        items: response.data,
        meta: response.meta
    }
}

export async function getListing(id) {
    const response = await client.get(`/items/listings/${id}`, {
        fields: DETAIL_FIELDS
    })
    return response.data
}

export async function createListing(data) {
    const response = await client.post('/items/listings', data)
    return response?.data || response
}

export async function updateListing(id, data) {
    const response = await client.patch(`/items/listings/${id}`, data)
    return response.data
}

export async function incrementListingViews(id) {
    const viewedKey = `dgray_viewed_${id}`
    if (sessionStorage.getItem(viewedKey)) {
        return null
    }

    try {
        const listing = await client.get(`/items/listings/${id}`, {
            fields: ['views']
        })
        const currentViews = listing.data?.views || 0
        const newViews = currentViews + 1

        await client.patch(`/items/listings/${id}`, {
            views: newViews
        })

        sessionStorage.setItem(viewedKey, 'true')
        return newViews
    } catch (error) {
        console.error('Failed to increment views:', error)
        return null
    }
}

export async function deleteListing(id) {
    return client.delete(`/items/listings/${id}`)
}

export async function getMyListings() {
    const response = await client.get('/items/listings', {
        fields: ['*', 'images.directus_files_id.id', 'category.id', 'category.name', 'location.name'],
        filter: { user_created: { _eq: '$CURRENT_USER' } },
        sort: ['-date_created']
    })
    return response.data || []
}

export async function searchListings(query, options = {}) {
    return getListings({
        search: query,
        ...options
    })
}

export async function getListingsByCategory(categoryId, options = {}) {
    return getListings({
        filter: {
            status: { _eq: 'published' },
            category: { _eq: categoryId }
        },
        ...options
    })
}

export async function getListingsByLocation(locationId, options = {}) {
    return getListings({
        filter: {
            status: { _eq: 'published' },
            location: { _eq: locationId }
        },
        ...options
    })
}
