import {
  Controller,
  Get,
  Post,
  Patch,
  Delete,
  Body,
  Param,
  Query,
  UseGuards,
  ParseUUIDPipe,
} from '@nestjs/common';
import { HotelService } from './hotel.service';
import { CreateHotelDto, UpdateHotelDto, PlaceholderHotelDto } from './dto';
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
import { PermissionGuard } from '../../auth/guards/permission.guard';
import { Permissions } from '../../auth/decorators/permissions.decorator';
import { AccessLevel, ModuleName } from '../../entities/role-permission.entity';
import { paginatedResponse, successResponse } from '../../common/responses/api-response';
import { PaginationDto } from '../../common/dto/pagination.dto';
import { Lookup } from '../../common/decorators/lookup.decorator';

@Controller('hotels')
@UseGuards(JwtAuthGuard, PermissionGuard)
export class HotelController {
  constructor(private readonly hotelService: HotelService) {}

  @Get()
  @Permissions({ module: ModuleName.HOTEL, accessLevel: AccessLevel.VIEW })
  async findAll(@Query() query: PaginationDto, @Query('destination_id') destinationId?: string) {
    const { items, meta } = await this.hotelService.findAll(query, { destinationId });
    return paginatedResponse(items, meta, 'Hotels fetched successfully');
  }

  @Get('lookup')
  @Lookup()
  async lookup() {
    const items = await this.hotelService.findAllForLookup();
    return successResponse(items, 'Hotels lookup');
  }

  /**
   * Find-or-create by typed name + destination — used by Quote/Booking
   * form auto-create on save. @Lookup() so any authed tenant user can
   * call (no hotel-master permission needed).
   */
  @Post('placeholder')
  @Lookup()
  async createPlaceholder(@Body() dto: PlaceholderHotelDto) {
    const result = await this.hotelService.createPlaceholder(dto);
    return successResponse(result, 'Hotel ready');
  }

  @Get(':id')
  @Permissions({ module: ModuleName.HOTEL, accessLevel: AccessLevel.VIEW })
  async findById(@Param('id', ParseUUIDPipe) id: string) {
    const data = await this.hotelService.findById(id);
    return successResponse(data, 'Hotel fetched successfully');
  }

  @Post()
  @Permissions({ module: ModuleName.HOTEL, accessLevel: AccessLevel.CREATE })
  async create(@Body() dto: CreateHotelDto) {
    const result = await this.hotelService.create(dto);
    return successResponse(result, result.message);
  }

  @Patch(':id')
  @Permissions({ module: ModuleName.HOTEL, accessLevel: AccessLevel.EDIT })
  async update(@Param('id', ParseUUIDPipe) id: string, @Body() dto: UpdateHotelDto) {
    const result = await this.hotelService.update(id, dto);
    return successResponse(result, result.message);
  }

  @Delete(':id')
  @Permissions({ module: ModuleName.HOTEL, accessLevel: AccessLevel.DELETE })
  async remove(@Param('id', ParseUUIDPipe) id: string) {
    const result = await this.hotelService.remove(id);
    return successResponse(result, result.message);
  }
}
