'use server'

import client from './config/sanity'

export async function getAllRooms() {
  const query = '*[_type == "roomType" && status=="online"]'
  const rooms = await client.fetch(query, {}, { cache: 'no-store' })
  console.log(rooms?.length)
  return {
    rooms,
  }
}

export async function getRoomDetails(roomId: string) {
  const query = '*[_type == "roomType" && _id == $roomId][0]'
  const room = await client.fetch(query, { roomId }, { cache: 'no-store' })

  return {
    room,
  }
}

// export async function addMultipleRooms() {
//     const rooms = [
//         {
//             _type: 'roomType',
//             roomType: 'Deluxe Suite',
//             price: 200,
//             totalCount: 10,
//             bookingCount: 2,
//             description: 'A luxurious room with a stunning view and premium amenities.',
//             images: [], // Add image references here
//         },
//         {
//             _type: 'roomType',
//             roomType: 'Standard Room',
//             price: 100,
//             totalCount: 20,
//             bookingCount: 5,
//             description: 'A comfortable room with all the basic facilities you need.',
//             images: [], // Add image references here
//         },
//         {
//             _type: 'roomType',
//             roomType: 'Family Suite',
//             price: 250,
//             totalCount: 5,
//             bookingCount: 1,
//             description: 'Spacious suite perfect for families, with multiple beds and a living area.',
//             images: [], // Add image references here
//         },
//         {
//             _type: 'roomType',
//             roomType: 'Single Room',
//             price: 80,
//             totalCount: 15,
//             bookingCount: 3,
//             description: 'A cozy room ideal for solo travelers.',
//             images: [], // Add image references here
//         },
//         {
//             _type: 'roomType',
//             roomType: 'Executive Suite',
//             price: 300,
//             totalCount: 8,
//             bookingCount: 4,
//             description: 'An executive suite with exclusive amenities and services.',
//             images: [], // Add image references here
//         }
//     ];

//     // Adding each room document to Sanity
//     const createdRooms = await Promise.all(
//         rooms.map(room => client.create(room))
//     );

//     return {
//         createdRooms
//     };
// }

export interface RoomBooking {
  _type: 'roomBooking'
  roomId: string
  roomType: string
  price: number
  totalCount: number
  bookingCount: number
  checkInDate: string // ISO 8601 string for datetime
  checkOutDate: string // ISO 8601 string for datetime
  guestName: string
  guestEmail: string
  guestPhone: string
  paymentStatus: 'pending' | 'completed' | 'failed'
  note?: string // Optional
  capacity: {
    adults: number
    children: number
  }
  status: string
}

export async function bookRoom(bookingDetails: RoomBooking) {
  const {
    roomId,
    checkInDate,
    checkOutDate,
    guestName,
    guestEmail,
    guestPhone,
    capacity,
    paymentStatus,
    note,
    price,
    totalCount,
    bookingCount,
  } = bookingDetails

  // Fetch the room details first
  const roomQuery = '*[_type == "roomType" && _id == $roomId][0]'
  const room = await client.fetch(roomQuery, { roomId }, { cache: 'no-store' })

  if (!room) {
    return { success: false, message: 'Room not found.' }
  }

  // Check if the room is available
  if (room.bookingCount >= room.totalCount) {
    return { success: false, message: 'No rooms available.' }
  }

  // Create a booking document
  const bookingDoc = {
    _type: 'roomBooking',
    roomId: roomId,
    roomType: room.roomType,
    checkInDate,
    checkOutDate,
    guestName,
    guestEmail,
    guestPhone,
    capacity,
    paymentStatus,
    note,
    price,
    totalCount,
    bookingCount,
  }

  const createdBooking = await client.create(bookingDoc)

  // Update the booking count of the room
  const updatedRoom = await client
    .patch(roomId)
    .set({ bookingCount: room.bookingCount + 1 })
    .commit()

  return {
    success: true,
    message: 'Room booked successfully.',
    booking: createdBooking,
    updatedRoom,
  }
}

export async function insertContact(contactData: {
  name: string
  email: string
  subject?: string
  message: string
}) {
  try {
    // Validate the input to ensure all required fields are provided
    const { name, email, subject, message } = contactData

    if (!name) throw new Error('Name is required')
    if (!email) throw new Error('Email is required')
    if (!message) throw new Error('Message is required')

    // Create a new contact document
    const newContact = {
      _type: 'contact',
      name,
      email,
      subject: subject || '', // If subject is optional, use an empty string if not provided
      message,
    }

    // Insert the document into Sanity
    const result = await client.create(newContact)

    console.log('Contact inserted:', result)
    return result
  } catch (error) {
    console.error('Failed to insert contact:')
    throw error
  }
}
