import { http, HttpResponse } from 'msw';

const API_BASE_URL = 'http://localhost:8000/api';

// Mock data
const mockBanners = [
  {
    id: 1,
    title: 'Welcome to Our Hotel',
    description: 'Experience luxury like never before',
    image_url: '/images/banner1.jpg',
    link_url: '/rooms',
    position: 'home',
    display_order: 1,
    is_active: true,
    created_at: '2024-01-01T00:00:00Z',
    updated_at: '2024-01-01T00:00:00Z',
  },
];

const mockRooms = [
  {
    id: 1,
    room_type_id: 1,
    room_number: '101',
    floor: 1,
    status: 'available',
    featured: true,
    price: 150,
    description: 'A beautiful room',
    capacity: 2,
    room_size: '30 sqm',
    view: 'Ocean',
    images: ['/images/room1.jpg'],
    amenities: ['WiFi', 'TV', 'AC'],
    created_at: '2024-01-01T00:00:00Z',
    updated_at: '2024-01-01T00:00:00Z',
    room_type: {
      id: 1,
      name: 'Deluxe Room',
      description: 'Spacious and comfortable',
      base_price: 150,
      capacity: 2,
      amenities: ['WiFi', 'TV', 'AC'],
      images: ['/images/room1.jpg'],
    },
    average_rating: 4.5,
    total_reviews: 10,
  },
  {
    id: 2,
    room_type_id: 2,
    room_number: '102',
    floor: 1,
    status: 'available',
    featured: false,
    price: 200,
    description: 'A luxurious suite',
    capacity: 4,
    room_size: '50 sqm',
    view: 'Garden',
    images: ['/images/room2.jpg'],
    amenities: ['WiFi', 'TV', 'AC', 'Minibar'],
    created_at: '2024-01-01T00:00:00Z',
    updated_at: '2024-01-01T00:00:00Z',
    room_type: {
      id: 2,
      name: 'Suite',
      description: 'Luxurious suite',
      base_price: 200,
      capacity: 4,
      amenities: ['WiFi', 'TV', 'AC', 'Minibar'],
      images: ['/images/room2.jpg'],
    },
    average_rating: 4.8,
    total_reviews: 5,
  },
];

const mockPageContent = {
  id: 1,
  page_type: 'home',
  title: 'Welcome to Our Hotel',
  subtitle: 'Experience Luxury',
  description: 'A beautiful hotel experience',
  hero_title: 'Featured & Newest Rooms',
  hero_subtitle: 'Discover our most popular accommodations',
  features: [
    { icon: 'Hotel', title: 'Easy Booking', description: 'Book with ease' },
    { icon: 'DollarSign', title: 'Best Prices', description: 'Best price guarantee' },
    { icon: 'Headphones', title: '24/7 Support', description: 'Always available' },
  ],
  amenities: [],
  testimonials: [],
  gallery_images: [],
  stats: [],
  luxury_features: [],
  luxury_gallery: [],
  luxury_testimonials: [],
  luxury_services: [],
  luxury_experiences: [],
  awards: [],
  partners: [],
  created_at: '2024-01-01T00:00:00Z',
  updated_at: '2024-01-01T00:00:00Z',
};

export const handlers = [
  // Banners
  http.get(`${API_BASE_URL}/banners`, ({ request }) => {
    const url = new URL(request.url);
    const position = url.searchParams.get('position');
    
    const filteredBanners = position
      ? mockBanners.filter(b => b.position === position)
      : mockBanners;

    return HttpResponse.json({
      status: 'success',
      data: {
        banners: filteredBanners,
      },
    });
  }),

  // Rooms
  http.get(`${API_BASE_URL}/rooms`, ({ request }) => {
    const url = new URL(request.url);
    const featured = url.searchParams.get('featured');
    const page = parseInt(url.searchParams.get('page') || '1');
    const limit = parseInt(url.searchParams.get('limit') || '10');

    let filteredRooms = [...mockRooms];
    
    if (featured === 'true') {
      filteredRooms = filteredRooms.filter(r => r.featured);
    }

    const start = (page - 1) * limit;
    const end = start + limit;
    const paginatedRooms = filteredRooms.slice(start, end);

    return HttpResponse.json({
      status: 'success',
      success: true,
      data: {
        rooms: paginatedRooms,
        pagination: {
          total: filteredRooms.length,
          page,
          limit,
          totalPages: Math.ceil(filteredRooms.length / limit),
        },
      },
    });
  }),

  http.get(`${API_BASE_URL}/rooms/id/:id`, ({ params }) => {
    const id = parseInt(params.id as string);
    const room = mockRooms.find(r => r.id === id);
    
    if (!room) {
      return HttpResponse.json(
        { status: 'error', message: 'Room not found' },
        { status: 404 }
      );
    }

    return HttpResponse.json({
      status: 'success',
      data: {
        room,
      },
    });
  }),

  http.get(`${API_BASE_URL}/rooms/:roomNumber`, ({ params }) => {
    const roomNumber = params.roomNumber as string;
    const room = mockRooms.find(r => r.room_number === roomNumber);
    
    if (!room) {
      return HttpResponse.json(
        { status: 'error', message: 'Room not found' },
        { status: 404 }
      );
    }

    return HttpResponse.json({
      status: 'success',
      data: {
        room,
      },
    });
  }),

  http.get(`${API_BASE_URL}/rooms/available`, () => {
    return HttpResponse.json({
      status: 'success',
      data: {
        rooms: mockRooms.filter(r => r.status === 'available'),
        pagination: {
          total: mockRooms.filter(r => r.status === 'available').length,
          page: 1,
          limit: 10,
          totalPages: 1,
        },
      },
    });
  }),

  http.get(`${API_BASE_URL}/rooms/amenities`, () => {
    return HttpResponse.json({
      status: 'success',
      data: {
        amenities: ['WiFi', 'TV', 'AC', 'Minibar', 'Room Service'],
      },
    });
  }),

  http.get(`${API_BASE_URL}/rooms/:roomId/booked-dates`, ({ params }) => {
    const roomId = parseInt(params.roomId as string);
    return HttpResponse.json({
      status: 'success',
      data: {
        room_id: roomId,
        booked_dates: [],
      },
    });
  }),

  // Page Content
  http.get(`${API_BASE_URL}/home`, () => {
    return HttpResponse.json({
      status: 'success',
      data: {
        page_content: mockPageContent,
      },
    });
  }),

  http.get(`${API_BASE_URL}/page-content/:pageType`, ({ params }) => {
    const pageType = params.pageType as string;
    return HttpResponse.json({
      status: 'success',
      data: {
        page_content: {
          ...mockPageContent,
          page_type: pageType,
        },
      },
    });
  }),

  // Health check
  http.get(`${API_BASE_URL}/health`, () => {
    return HttpResponse.json({
      status: 'success',
      message: 'API is healthy',
    });
  }),

  // Auth endpoints (basic mocks)
  http.post(`${API_BASE_URL}/auth/login`, async ({ request }) => {
    const body = await request.json() as any;
    if (body.email && body.password) {
      return HttpResponse.json({
        status: 'success',
        data: {
          token: 'mock-token',
          user: {
            id: 1,
            email: body.email,
            role: 'customer',
          },
        },
      });
    }
    return HttpResponse.json(
      { status: 'error', message: 'Invalid credentials' },
      { status: 401 }
    );
  }),

  http.post(`${API_BASE_URL}/auth/register`, async ({ request }) => {
    const body = await request.json() as any;
    return HttpResponse.json({
      status: 'success',
      data: {
        token: 'mock-token',
        user: {
          id: 1,
          email: body.email,
          role: 'customer',
        },
      },
    });
  }),

  // Bookings
  http.get(`${API_BASE_URL}/bookings`, ({ request }) => {
    const url = new URL(request.url);
    const page = parseInt(url.searchParams.get('page') || '1');
    const limit = parseInt(url.searchParams.get('limit') || '10');
    
    const mockBookings = [
      {
        id: 1,
        user_id: 1,
        room_id: 1,
        check_in: '2024-02-01T00:00:00Z',
        check_out: '2024-02-05T00:00:00Z',
        check_in_date: '2024-02-01T00:00:00Z',
        check_out_date: '2024-02-05T00:00:00Z',
        status: 'confirmed',
        total_price: 600,
        created_at: '2024-01-15T00:00:00Z',
        updated_at: '2024-01-15T00:00:00Z',
        customer_name: 'Test Customer',
        customer_email: 'test@example.com',
        guest_info: {
          name: 'Test Customer',
          email: 'test@example.com',
        },
        user: {
          id: 1,
          email: 'test@example.com',
        },
        room: mockRooms[0],
        payments: [],
      },
    ];

    return HttpResponse.json({
      status: 'success',
      success: true,
      data: {
        bookings: mockBookings,
        pagination: {
          total: mockBookings.length,
          page,
          limit,
          totalPages: Math.ceil(mockBookings.length / limit),
        },
      },
    });
  }),

  http.get(`${API_BASE_URL}/bookings/:id`, ({ params }) => {
    const id = parseInt(params.id as string);
    return HttpResponse.json({
      status: 'success',
      data: {
        booking: {
          id,
          user_id: 1,
          room_id: 1,
          check_in: '2024-02-01T00:00:00Z',
          check_out: '2024-02-05T00:00:00Z',
          check_in_date: '2024-02-01T00:00:00Z',
          check_out_date: '2024-02-05T00:00:00Z',
          status: 'confirmed',
          total_price: 600,
          created_at: '2024-01-15T00:00:00Z',
          updated_at: '2024-01-15T00:00:00Z',
          customer_name: 'Test Customer',
          customer_email: 'test@example.com',
          room: mockRooms[0],
        },
      },
    });
  }),

  // Payments
  http.get(`${API_BASE_URL}/payments`, ({ request }) => {
    const url = new URL(request.url);
    const page = parseInt(url.searchParams.get('page') || '1');
    const limit = parseInt(url.searchParams.get('limit') || '10');
    
    const mockPayments = [
      {
        id: 1,
        booking_id: 1,
        amount: 600,
        payment_method: 'stripe',
        payment_status: 'completed',
        payment_type: 'full',
        transaction_id: 'txn_123',
        created_at: '2024-01-15T00:00:00Z',
        updated_at: '2024-01-15T00:00:00Z',
      },
    ];

    return HttpResponse.json({
      status: 'success',
      success: true,
      data: {
        payments: mockPayments,
        pagination: {
          total: mockPayments.length,
          page,
          limit,
          totalPages: Math.ceil(mockPayments.length / limit),
        },
      },
    });
  }),

  // Invoices
  http.get(`${API_BASE_URL}/invoices`, ({ request }) => {
    const url = new URL(request.url);
    const page = parseInt(url.searchParams.get('page') || '1');
    const limit = parseInt(url.searchParams.get('limit') || '10');
    
    const mockInvoices = [
      {
        id: 1,
        booking_id: 1,
        invoice_number: 'INV-001',
        total_amount: 600,
        status: 'paid',
        customer_name: 'Test Customer',
        customer_email: 'test@example.com',
        issue_date: '2024-01-15T00:00:00Z',
        due_date: '2024-02-15T00:00:00Z',
        created_at: '2024-01-15T00:00:00Z',
        updated_at: '2024-01-15T00:00:00Z',
      },
    ];

    return HttpResponse.json({
      status: 'success',
      data: {
        invoices: mockInvoices,
        pagination: {
          total: mockInvoices.length,
          page,
          limit,
          totalPages: Math.ceil(mockInvoices.length / limit),
        },
      },
    });
  }),

  // Dashboard Service
  http.get(`${API_BASE_URL}/dashboard/customer`, () => {
    return HttpResponse.json({
      status: 'success',
      data: {
        total_bookings: 5,
        upcoming_bookings: 2,
        completed_bookings: 3,
        total_spent: 3000,
      },
    });
  }),

  http.get(`${API_BASE_URL}/reports/customer/dashboard`, () => {
    return HttpResponse.json({
      status: 'success',
      data: {
        total_bookings: 5,
        upcoming_bookings: 2,
        completed_bookings: 3,
        total_spent: 3000,
      },
    });
  }),

  // Reports Service
  http.get(`${API_BASE_URL}/reports`, () => {
    return HttpResponse.json({
      status: 'success',
      data: {
        total_revenue: 50000,
        total_bookings: 100,
        total_rooms: 50,
        occupancy_rate: 75.5,
        average_booking_value: 500,
        revenue_by_month: [],
        bookings_by_status: {
          confirmed: 60,
          pending: 20,
          cancelled: 20,
        },
      },
    });
  }),

  // Users
  http.get(`${API_BASE_URL}/admin/users`, ({ request }) => {
    const url = new URL(request.url);
    const page = parseInt(url.searchParams.get('page') || '1');
    const limit = parseInt(url.searchParams.get('limit') || '10');
    
    const mockUsers = [
      {
        id: 1,
        email: 'user@example.com',
        role: 'customer',
        created_at: '2024-01-01T00:00:00Z',
      },
    ];

    return HttpResponse.json({
      status: 'success',
      data: {
        users: mockUsers,
        pagination: {
          total: mockUsers.length,
          page,
          limit,
          totalPages: Math.ceil(mockUsers.length / limit),
        },
      },
    });
  }),

  http.get(`${API_BASE_URL}/users`, ({ request }) => {
    const url = new URL(request.url);
    const page = parseInt(url.searchParams.get('page') || '1');
    const limit = parseInt(url.searchParams.get('limit') || '10');
    
    const mockUsers = [
      {
        id: 1,
        email: 'user@example.com',
        name: 'Test User',
        role: 'customer',
        phone: '+1234567890',
        status: 'active',
        created_at: '2024-01-01T00:00:00Z',
      },
    ];

    return HttpResponse.json({
      status: 'success',
      data: {
        users: mockUsers,
        pagination: {
          total: mockUsers.length,
          page,
          limit,
          totalPages: Math.ceil(mockUsers.length / limit),
        },
      },
    });
  }),

  // Services
  http.get(`${API_BASE_URL}/services`, ({ request }) => {
    const url = new URL(request.url);
    const page = parseInt(url.searchParams.get('page') || '1');
    const limit = parseInt(url.searchParams.get('limit') || '10');
    
    const mockServices = [
      {
        id: 1,
        name: 'Room Service',
        description: '24/7 room service',
        price: 25,
        unit: 'time',
        status: 'active',
      },
    ];

    return HttpResponse.json({
      status: 'success',
      data: {
        services: mockServices,
        pagination: {
          total: mockServices.length,
          page,
          limit,
          totalPages: Math.ceil(mockServices.length / limit),
        },
      },
    });
  }),

  // Favorites
  http.get(`${API_BASE_URL}/favorites`, () => {
    return HttpResponse.json({
      status: 'success',
      data: {
        favorites: [],
      },
    });
  }),

  // Reviews
  http.get(`${API_BASE_URL}/rooms/:roomId/reviews`, () => {
    return HttpResponse.json({
      status: 'success',
      data: {
        reviews: [],
        pagination: {
          total: 0,
          page: 1,
          limit: 10,
          totalPages: 0,
        },
      },
    });
  }),

  // System Settings
  http.get(`${API_BASE_URL}/admin/system-settings/company`, () => {
    return HttpResponse.json({
      status: 'success',
      data: {
        company_name: 'Test Hotel',
        company_logo: '/images/logo.png',
        company_email: 'test@hotel.com',
        company_phone: '+1234567890',
        company_address: '123 Test Street',
      },
    });
  }),

  http.get(`${API_BASE_URL}/admin/system-settings/currency`, () => {
    return HttpResponse.json({
      status: 'success',
      data: {
        currency: 'USD',
      },
    });
  }),

  // Privacy/Cookie Consent
  http.get(`${API_BASE_URL}/privacy/cookie-consent`, () => {
    return HttpResponse.json({
      status: 'success',
      data: {
        has_decided: false,
        necessary: true,
        analytics: false,
        marketing: false,
      },
    });
  }),

  // Handle OPTIONS requests (CORS preflight)
  http.options(`${API_BASE_URL}/*`, () => {
    return HttpResponse.json({}, { status: 200 });
  }),
];

