import {
  Body,
  Controller,
  Delete,
  Get,
  HttpStatus,
  Param,
  Patch,
  Post,
  Query,
  Req,
  Res,
  UseGuards,
  UsePipes,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { CurrentUser } from '../../common/decorators/current-user.decorator';
import { ZodValidationPipe } from '../../common/pipes/zod-validation.pipe';
import { JwtAuthGuard } from '../owner/guards/jwt.guard';
import {
  DeviceChangeFilterDto,
  RequestDeviceChangeDto,
  ReviewDeviceChangeDto,
  deviceChangeFilterSchema,
  requestDeviceChangeSchema,
  reviewDeviceChangeSchema,
} from './devices.dto';
import { DevicesService } from './devices.service';

@Controller('devices')
@UseGuards(JwtAuthGuard)
export class DevicesController {
  constructor(private readonly service: DevicesService) {}

  @Post('request-change')
  @UsePipes(new ZodValidationPipe(requestDeviceChangeSchema))
  async requestChange(
    @Body() body: RequestDeviceChangeDto,
    @CurrentUser() owner_id: string,
    @Req() req: Request,
    @Res() res: Response,
  ) {
    const user: any = req.user;
    const memberId = user?.sub || user?.id;
    const result = await this.service.requestDeviceChange(
      memberId,
      owner_id,
      body,
    );
    return res.status(result.status).json(result);
  }

  @Get('my-device')
  async getMyDevice(
    @CurrentUser() owner_id: string,
    @Req() req: Request,
    @Res() res: Response,
  ) {
    const user: any = req.user;
    const memberId = user?.sub || user?.id;
    const result = await this.service.getMyDevice(memberId, owner_id);
    return res.status(result.status).json(result);
  }

  @Get('requests')
  @UsePipes(new ZodValidationPipe(deviceChangeFilterSchema))
  async getRequests(
    @Query() query: DeviceChangeFilterDto,
    @CurrentUser() owner_id: string,
    @Res() res: Response,
  ) {
    const result = await this.service.getDeviceChangeRequests(owner_id, query);
    return res.status(result.status).json(result);
  }

  @Patch('requests/:id/review')
  @UsePipes(new ZodValidationPipe(reviewDeviceChangeSchema))
  async reviewRequest(
    @Param('id') id: string,
    @Body() body: ReviewDeviceChangeDto,
    @CurrentUser() owner_id: string,
    @Req() req: Request,
    @Res() res: Response,
  ) {
    const user: any = req.user;
    const reviewerId = user?.sub || user?.id;
    const result = await this.service.reviewDeviceChangeRequest(
      id,
      owner_id,
      reviewerId,
      body,
    );
    return res.status(result.status).json(result);
  }

  @Delete('reset/:memberId')
  async resetDevice(
    @Param('memberId') memberId: string,
    @CurrentUser() owner_id: string,
    @Res() res: Response,
  ) {
    const result = await this.service.resetDeviceBinding(memberId, owner_id);
    return res.status(result.status).json(result);
  }
}
