import {
  Controller,
  Get,
  Post,
  Query,
  UseGuards,
  HttpCode,
  HttpStatus,
} from '@nestjs/common';
import { SyncService } from './sync.service';
import { ScheduledSyncService } from './scheduled-sync.service';
import { PrismaService } from '@core/database/prisma/prisma.service';
import { PermissionsGuard } from '../auth/guards/permissions.guard';
import { RequirePermissions } from '@common/decorators/permissions.decorator';
import { Auditable, Sensitive } from '@core/observability/audit/decorators/auditable.decorator';

const TASK_CODE = 'ENTRA_ID_SYNC';

@Controller('organization')
export class SyncController {
  constructor(
    private readonly syncService: SyncService,
    private readonly scheduledSyncService: ScheduledSyncService,
    private readonly prisma: PrismaService,
  ) {}

  /**
   * POST /api/v1/organization/sync
   * 手动触发 Entra ID 同步
   */
  @Post('sync')
  @Auditable()
  @Sensitive()
  @HttpCode(HttpStatus.OK)
  @RequirePermissions('organization:sync')
  async syncFromEntraId() {
    return this.scheduledSyncService.triggerManualSync();
  }

  /**
   * GET /api/v1/organization/sync/status
   */
  @Get('sync/status')
  @RequirePermissions('organization:sync')
  async getSyncStatus() {
    return this.syncService.getSyncStatus();
  }

  /**
   * GET /api/v1/organization/sync/executions
   * 查询 Entra ID 同步执行历史（分页 + 日期筛选）
   */
  @Get('sync/executions')
  @RequirePermissions('organization:sync')
  async getSyncExecutions(
    @Query('page') page?: string,
    @Query('limit') limit?: string,
    @Query('startDate') startDate?: string,
    @Query('endDate') endDate?: string,
    @Query('hideEmpty') hideEmpty?: string,
  ) {
    const pageNum = parseInt(page || '1');
    const pageSize = parseInt(limit || '20');

    const taskFilter: any = { code: TASK_CODE };
    const where: any = { task: { is: taskFilter } };

    if (startDate || endDate) {
      where.startedAt = {};
      if (startDate) where.startedAt.gte = new Date(startDate);
      if (endDate) {
        const end = new Date(endDate);
        end.setHours(23, 59, 59, 999);
        where.startedAt.lte = end;
      }
    }

    // 隐藏无变化记录（createdUsers + updatedUsers = 0）
    if (hideEmpty === 'true') {
      where.OR = [
        { result: { path: ['createdUsers'], gt: 0 } },
        { result: { path: ['updatedUsers'], gt: 0 } },
      ];
    }

    const [executions, total] = await Promise.all([
      this.prisma.automationExecution.findMany({
        where,
        orderBy: { startedAt: 'desc' },
        skip: (pageNum - 1) * pageSize,
        take: pageSize,
      }),
      this.prisma.automationExecution.count({ where }),
    ]);

    return {
      items: executions.map(e => ({
        id: e.id,
        status: e.status,
        startedAt: e.startedAt,
        completedAt: e.completedAt,
        duration: e.duration,
        triggerType: e.triggerType,
        error: e.error,
        result: e.result,
        logs: e.logs,
      })),
      total,
      page: pageNum,
      limit: pageSize,
    };
  }

  /**
   * GET /api/v1/organization/stats
   */
  @Get('stats')
  async getStats() {
    return this.syncService.getOrganizationStats();
  }
}
