import { Controller, Get, Logger, HttpException, HttpStatus } from '@nestjs/common';
import { CronService, DateIvtGroups } from './cron.service';
import { MessageService } from './message.service';

@Controller('cron')
export class CronController {
  private readonly logger = new Logger(CronController.name);

  constructor(
    private readonly cronService: CronService,
    private readonly messageService: MessageService,
  ) {}

  @Get('test-grouping')
  async testGrouping(): Promise<{
    message: string;
    timestamp: string;
    groups: {
      inTwoDays: number;
      passedOneDay: number;
      passedBetweenTwoAndSixDays: number;
      passedSevenDays: number;
      passedMoreThanSevenDays: number;
    };
    details: DateIvtGroups;
  }> {
    this.logger.log('Manual test of Date IVT grouping triggered');
    const groups = await this.cronService.testGrouping();

    return {
      message: 'Date IVT grouping test completed',
      timestamp: new Date().toISOString(),
      groups: {
        inTwoDays: groups.inTwoDays.length,
        passedOneDay: groups.passedOneDay.length,
        passedBetweenTwoAndSixDays: groups.passedBetweenTwoAndSixDays.length,
        passedSevenDays: groups.passedSevenDays.length,
        passedMoreThanSevenDays: groups.passedMoreThanSevenDays.length,
      },
      details: groups,
    };
  }

  @Get('trigger-manual')
  async triggerManual(): Promise<{
    message: string;
    timestamp: string;
    status: 'success' | 'error';
    error?: string;
  }> {
    this.logger.log('Manual trigger of Date IVT processing');
    
    try {
      await this.cronService.processDateIvtRecords();

      return {
        message: 'Manual Date IVT processing completed successfully',
        timestamp: new Date().toISOString(),
        status: 'success',
      };
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      this.logger.error('Error during manual trigger:', error);
      
      throw new HttpException(
        {
          message: 'Error during manual Date IVT processing',
          timestamp: new Date().toISOString(),
          status: 'error',
          error: errorMessage,
        },
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  @Get('test-messages')
  async testMessages() {
    this.logger.log('Manual test of SMS message sending');
    await this.cronService.testMessageSending();

    return {
      message: 'SMS message sending test completed',
      timestamp: new Date().toISOString(),
    };
  }
}
