import {
  Controller,
  Get,
  Post,
  Delete,
  Param,
  Body,
  Query,
  UseGuards,
  HttpStatus,
  ParseUUIDPipe,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth, ApiQuery } from '@nestjs/swagger';
import { HistoryService } from './history.service';
import { UpsertHistoryDto } from './dto/upsert-history.dto';
import { JwtAuthGuard } from '../common/guards/jwt-auth.guard';
import { CurrentUser } from '../common/decorators/current-user.decorator';

@ApiTags('History')
@Controller('history')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
export class HistoryController {
  constructor(private readonly historyService: HistoryService) {}

  @Get()
  @ApiOperation({ summary: 'Get user watch history' })
  @ApiQuery({ name: 'page', required: false, type: Number })
  @ApiQuery({ name: 'limit', required: false, type: Number })
  async findAll(
    @CurrentUser('id') userId: string,
    @Query('page') page: string = '1',
    @Query('limit') limit: string = '20',
  ) {
    const result = await this.historyService.findAllByUser(userId, {
      page: Math.max(1, parseInt(page, 10) || 1),
      limit: Math.min(100, Math.max(1, parseInt(limit, 10) || 20)),
    });

    return {
      ...result,
      message: 'History retrieved successfully',
      statusCode: HttpStatus.OK,
    };
  }

  @Get('continue-watching')
  @ApiOperation({ summary: 'Get continue watching items' })
  async getContinueWatching(@CurrentUser('id') userId: string) {
    const items = await this.historyService.getContinueWatching(userId);
    return {
      data: items,
      message: 'Continue watching items retrieved successfully',
      statusCode: HttpStatus.OK,
    };
  }

  @Post()
  @ApiOperation({ summary: 'Record or update watch history' })
  async upsert(
    @CurrentUser('id') userId: string,
    @Body() upsertHistoryDto: UpsertHistoryDto,
  ) {
    const history = await this.historyService.upsert(userId, upsertHistoryDto);
    return {
      data: history,
      message: 'History recorded successfully',
      statusCode: HttpStatus.OK,
    };
  }

  @Delete(':id')
  @ApiOperation({ summary: 'Delete history entry' })
  async remove(
    @CurrentUser('id') userId: string,
    @Param('id', ParseUUIDPipe) id: string,
  ) {
    await this.historyService.remove(id, userId);
    return {
      data: null,
      message: 'History entry deleted successfully',
      statusCode: HttpStatus.OK,
    };
  }
}
