import { databases, client, config } from './appwrite';
import { ID, Query } from 'react-native-appwrite'

// Car type based on your database schema
interface Car {
    id: string;
    title: string;
    description: string;
    price: number;
    make: string;
    model: string;
    year: number;
    fuelType: 'Petrol' | 'Diesel' | 'Electric' | 'Hybrid';
    transmission: 'Manual' | 'Automatic';
    location: string;
    postedBy: string;
    createdAt: string;
    images: string[];
    featured: boolean;
}

// Car functions
export async function createCar(carData: Omit<Car, 'id' | 'createdAt'>) {
    try {
        return await databases.createDocument(
            config.databaseId!,
            config.carId!,
            ID.unique(),
            {
                ...carData,
                createdAt: new Date().toISOString(),
            }
        );
    } catch (error) {
        console.error('Error creating car:', error);
        throw error;
    }
}

export async function getCars(searchQuery?: string) {
    try {
        const queries = [Query.orderDesc('$createdAt')];
        
        if (searchQuery) {
            const searchTerm = searchQuery.toLowerCase();
            queries.push(
                Query.search('title', searchTerm)
            );
        }

        const response = await databases.listDocuments(
            config.databaseId!,
            config.carId!,
            queries
        );
        return response.documents;
    } catch (error) {
        console.error('Error fetching cars:', error);
        throw error;
    }
}

export async function getFeaturedCars() {
    try {
        const response = await databases.listDocuments(
            config.databaseId!,
            config.carId!,
            [
                Query.orderDesc('$createdAt'),
                Query.limit(5)
            ]
        );
        return response.documents;
    } catch (error) {
        console.error('Error fetching featured cars:', error);
        throw error;
    }
}

export async function getCar(id: string) {
    try {
        const response = await databases.getDocument(
            config.databaseId!,
            config.carId!,
            id
        );
        return response;
    } catch (error) {
        console.error('Error fetching car:', error);
        throw error;
    }
}

// Favorites functions
export async function toggleFavorite(userId: string, carId: string) {
    try {
        const favorite = await databases.listDocuments(
            config.databaseId!,
            'favorites',
            [
                Query.equal('userId', userId),
                Query.equal('carId', carId)
            ]
        );

        if (favorite.documents.length > 0) {
            await databases.deleteDocument(
                config.databaseId!,
                'favorites',
                favorite.documents[0].$id
            );
            return false; // Unfavorited
        } else {
            await databases.createDocument(
                config.databaseId!,
                'favorites',
                ID.unique(),
                {
                    userId,
                    carId,
                    createdAt: new Date().toISOString()
                }
            );
            return true; // Favorited
        }
    } catch (error) {
        console.error('Error toggling favorite:', error);
        throw error;
    }
}