import {
  Controller,
  Get,
  Post,
  Body,
  Param,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { RecruiterCvUsageService } from './recruiter_cv_usage.service';
import { Public } from '../auth/public.decorator';
import {
  ApiBearerAuth,
  ApiTags,
  ApiBody,
  ApiParam,
  ApiQuery,
  ApiOperation,
} from '@nestjs/swagger';

@ApiTags('recruiter_cv_usage')
@ApiBearerAuth('access-token')
@Controller('recruiter_cv_usage')
export class RecruiterCvUsageController {
  constructor(
    private readonly recruiterCvUsageService: RecruiterCvUsageService,
  ) {}
  @Public()
  @Get('all')
  @ApiOperation({ summary: 'Get all usages' })
  async getAllUsages() {
    try {
      const result = await this.recruiterCvUsageService.getAllUsages();
      if (!result.success) {
        throw new HttpException(result.error, HttpStatus.BAD_REQUEST);
      }
      return result.data;
    } catch (error: any) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  @Public()
  @Get(':recruiterId')
  @ApiOperation({ summary: 'Get usage by recruiter ID' })
  @ApiParam({ name: 'recruiterId', type: String })
  async getUsageByRecruiterId(@Param('recruiterId') recruiterId: string) {
    try {
      let result = await this.recruiterCvUsageService.getUsageByRecruiterId(
        parseInt(recruiterId),
      );

      // If no usage record exists, automatically initialize with free plan (100 CV limit)
      if (result.success && !result.data) {
        const initResult =
          await this.recruiterCvUsageService.initializeRecruiterUsage(
            parseInt(recruiterId),
          );
        if (initResult.success) {
          result = await this.recruiterCvUsageService.getUsageByRecruiterId(
            parseInt(recruiterId),
          );
        }
      }

      if (!result.success) {
        throw new HttpException(result.error, HttpStatus.BAD_REQUEST);
      }

      return result.data || null;
    } catch (error: any) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  @Public()
  @Post('initialize')
  @ApiOperation({ summary: 'Initialize Recruiter Usage' })
  @ApiBody({
    schema: {
      type: 'object',
      properties: { recruiterId: { type: 'number' } },
      required: ['recruiterId'],
    },
  })
  async initializeRecruiterUsage(@Body() body: { recruiterId: number }) {
    try {
      const result =
        await this.recruiterCvUsageService.initializeRecruiterUsage(
          body.recruiterId,
        );
      if (!result.success) {
        throw new HttpException(result.error, HttpStatus.BAD_REQUEST);
      }
      return result;
    } catch (error: any) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  @Public()
  @Post('check-limit')
  @ApiOperation({ summary: 'Check Download Limit' })
  @ApiBody({
    schema: {
      type: 'object',
      properties: { recruiterId: { type: 'number' } },
      required: ['recruiterId'],
    },
  })
  async checkDownloadLimit(@Body() body: { recruiterId: number }) {
    try {
      const result = await this.recruiterCvUsageService.checkDownloadLimit(
        body.recruiterId,
      );
      return result;
    } catch (error: any) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  @Public()
  @Post('increment')
  @ApiOperation({ summary: 'Increment Download Count' })
  @ApiBody({
    schema: {
      type: 'object',
      properties: { recruiterId: { type: 'number' } },
      required: ['recruiterId'],
    },
  })
  async incrementDownloadCount(@Body() body: { recruiterId: number }) {
    try {
      const result = await this.recruiterCvUsageService.incrementDownloadCount(
        body.recruiterId,
      );
      if (!result.success) {
        throw new HttpException(result.error, HttpStatus.BAD_REQUEST);
      }
      return result;
    } catch (error: any) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  @Public()
  @Post('upgrade')
  @ApiOperation({ summary: 'Upgrade Recruiter Plan' })
  @ApiBody({
    schema: {
      type: 'object',
      properties: {
        recruiterId: { type: 'number' },
        planType: { type: 'string' },
        newLimit: { type: 'number' },
        planEndDate: { type: 'string', format: 'date-time' },
      },
      required: ['recruiterId', 'planType', 'newLimit'],
    },
  })
  async upgradePlan(
    @Body()
    body: {
      recruiterId: number;
      planType: string;
      newLimit: number;
      planEndDate?: string;
    },
  ) {
    try {
      const planEndDate = body.planEndDate
        ? new Date(body.planEndDate)
        : undefined;
      const result = await this.recruiterCvUsageService.upgradePlan(
        body.recruiterId,
        body.planType,
        body.newLimit,
        planEndDate,
      );
      if (!result.success) {
        throw new HttpException(result.error, HttpStatus.BAD_REQUEST);
      }
      return result;
    } catch (error: any) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  @Public()
  @Post('reset')
  @ApiOperation({ summary: 'Reset Usage' })
  @ApiBody({
    schema: {
      type: 'object',
      properties: { recruiterId: { type: 'number' } },
      required: ['recruiterId'],
    },
  })
  async resetUsage(@Body() body: { recruiterId: number }) {
    try {
      const result = await this.recruiterCvUsageService.resetUsage(
        body.recruiterId,
      );
      if (!result.success) {
        throw new HttpException(result.error, HttpStatus.BAD_REQUEST);
      }
      return result;
    } catch (error: any) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}
