import { Controller, Get, Post, Body, UseGuards, Res, Req, Patch, Param } from '@nestjs/common';
import { PagerService } from '../providers/pager.service';
import { CreatePagerDto } from '../dto/create-pager.dto';
import { OptionalAuthGuard } from '../../auth/guards/optinalAuth.guard';
import { RestId } from 'src/common/decorators/rest-id.decorator';
import { UserId } from 'src/common/decorators/user-id.decorator';
import { RestSlug } from 'src/common/decorators/rest-slug.decorator';
import { ApiTags, ApiOperation, ApiBody, ApiHeader, ApiBearerAuth, ApiParam } from '@nestjs/swagger';
import type { FastifyReply, FastifyRequest } from 'fastify';
import { AdminAuthGuard } from '../../auth/guards/adminAuth.guard';
import { AdminId } from 'src/common/decorators/admin-id.decorator';
import { UpdatePagerStatusDto } from '../dto/update-pager.dto';
import { PagerMessage } from 'src/common/enums/message.enum';
import { Permissions } from 'src/common/decorators/permissions.decorator';
import { Permission } from 'src/common/enums/permission.enum';
import { API_HEADER_SLUG } from 'src/common/constants';

@ApiTags('pager')
@Controller()
export class PagerController {
  constructor(private readonly pagerService: PagerService) { }

  @UseGuards(OptionalAuthGuard)
  @Post('public/pager')
  @ApiOperation({ summary: 'Create a new pager request' })
  @ApiHeader({ name: 'X-Slug', required: true, description: 'Restaurant slug identifier' })
  @ApiHeader({ name: 'Authorization', required: false, description: 'Bearer token (optional authentication)' })
  @ApiBody({ type: CreatePagerDto })
  async create(
    @Body() createPagerDto: CreatePagerDto,
    @Req() request: FastifyRequest,
    @Res() reply: FastifyReply,
    @RestSlug() slug: string,
    @RestId() restId?: string,
    @UserId() userId?: string,
  ) {
    // Convert empty strings to undefined for cleaner validation
    const normalizedRestId = restId || undefined;
    const normalizedUserId = userId || undefined;
    const userCookieId = request.cookies['pagerId'] || undefined;

    const pager = await this.pagerService.create(createPagerDto, {
      restId: normalizedRestId,
      userId: normalizedUserId,
      userCookieId,
      slug,
    });
    reply.setCookie('pagerId', pager.cookieId, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      maxAge: 1000 * 60 * 60 * 24 * 1, // 1 days
      path: '/',
    });
    return reply.code(200).send({
      success: true,
      message: PagerMessage.CREATED_SUCCESS,
      data: null,
    });
  }


  @UseGuards(OptionalAuthGuard)
  @Get('public/pager')
  @ApiOperation({ summary: 'Get all pager requests for the current session' })
  @ApiHeader(API_HEADER_SLUG)
  @ApiHeader({ name: 'Authorization', required: false, description: 'Bearer token (optional authentication)' })
  async findAll(@Req() request: FastifyRequest) {
    const cookieId = request.cookies['pagerId'] || undefined;
    if (!cookieId) {
      return [];
    }
    return this.pagerService.findAll(cookieId);
  }

  /********************  Admin Routes **********************/

  @UseGuards(AdminAuthGuard)
  @Permissions(Permission.MANAGE_PAGER)
  @ApiBearerAuth()
  @Get('admin/pager')
  @ApiOperation({ summary: 'Get all pager requests for the restaurant' })
  async findAllAdmin(@RestId() restId: string) {
    return this.pagerService.findAllByRestaurantId(restId);
  }

  @UseGuards(AdminAuthGuard)
  @Permissions(Permission.MANAGE_PAGER)
  @ApiBearerAuth()
  @Patch('admin/pager/:pagerId/status')
  @ApiParam({ name: 'pagerId', required: true, type: String })
  @ApiOperation({ summary: 'Update the status of a pager request' })
  @ApiBody({ type: UpdatePagerStatusDto })
  async updateStatus(
    @Param('pagerId') pagerId: string,
    @RestId() restId: string,
    @AdminId() adminId: string,
    @Body() dto: UpdatePagerStatusDto,
  ) {
    return this.pagerService.updateStatus(pagerId, restId, adminId, dto.status);
  }
}
