import { Controller, Get, Post, Query, HttpException, HttpStatus } from '@nestjs/common';
import { CronService } from './cron.service';
import { Public } from '../auth/public.decorator';
import { DataSource } from 'typeorm';

@Controller('admin/email-logs')
export class EmailLogsController {
  constructor(
    private readonly cronService: CronService,
    private readonly dataSource: DataSource,
  ) {}

  @Public()
  @Get()
  async getLogs(
    @Query('page') page = 1,
    @Query('limit') limit = 10,
    @Query('recipient_type') recipientType?: string,
    @Query('search') search?: string,
    @Query('status') status?: string,
  ) {
    try {
      const p = Math.max(1, Number(page));
      const l = Math.max(1, Number(limit));
      const offset = (p - 1) * l;

      let countQuery = `SELECT COUNT(*) as total FROM email_sending_logs WHERE 1=1`;
      let dataQuery = `
        SELECT l.*, 
          GROUP_CONCAT(j.job_post_id) as job_ids
        FROM email_sending_logs l
        LEFT JOIN email_sending_log_jobs j ON j.log_id = l.id
        WHERE 1=1
      `;
      const params: any[] = [];

      if (recipientType) {
        countQuery += ` AND recipient_type = ?`;
        dataQuery += ` AND l.recipient_type = ?`;
        params.push(recipientType);
      }

      if (status) {
        countQuery += ` AND status = ?`;
        dataQuery += ` AND l.status = ?`;
        params.push(status);
      }

      if (search) {
        countQuery += ` AND (recipient_email LIKE ? OR recipient_name LIKE ?)`;
        dataQuery += ` AND (l.recipient_email LIKE ? OR l.recipient_name LIKE ?)`;
        params.push(`%${search}%`, `%${search}%`);
      }

      const countResult = await this.dataSource.query(countQuery, params);
      const total = Number(countResult[0]?.total || 0);

      dataQuery += ` GROUP BY l.id ORDER BY l.sent_at DESC LIMIT ? OFFSET ?`;
      const dataParams = [...params, l, offset];
      const data = await this.dataSource.query(dataQuery, dataParams);

      return {
        success: true,
        data: data.map((item: any) => ({
          ...item,
          job_ids: item.job_ids ? item.job_ids.split(',').map(Number) : []
        })),
        total,
        page: p,
        limit: l,
      };
    } catch (error: any) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  @Public()
  @Post('trigger')
  async triggerCron() {
    try {
      this.cronService.handlePeriodicMatchingEmails().catch(err => {
        console.error('Triggered matching emails failed:', err);
      });
      return {
        success: true,
        message: 'Email matching cron job manually triggered in the background',
      };
    } catch (error: any) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}
