import {
  Controller,
  Post,
  Body,
  UseGuards,
  Logger,
} from '@nestjs/common';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../auth/guards/roles.guard';
import { Roles } from '../auth/decorators/roles.decorator';
import { Role } from '@prisma/client';
import { CurrentUser } from '../auth/decorators/current-user.decorator';
import { CopilotService } from './copilot.service';

interface ChatMessageDto {
  role: 'user' | 'assistant';
  content: string | any[];
}

interface ChatRequestDto {
  messages: ChatMessageDto[];
}

@Controller('copilot')
@UseGuards(JwtAuthGuard, RolesGuard)
export class CopilotController {
  private readonly logger = new Logger(CopilotController.name);

  constructor(private readonly copilotService: CopilotService) {}

  @Post('chat')
  @Roles(Role.ADMINISTRATOR, Role.COORDINATOR)
  async chat(
    @Body() body: ChatRequestDto,
    @CurrentUser() user: any,
  ) {
    this.logger.log(`Copilot chat request from user: ${user.email}`);

    try {
      const result = await this.copilotService.chat(
        body.messages,
        user.id,
        user.role,
      );

      return {
        success: true,
        ...result,
      };
    } catch (error) {
      this.logger.error('Copilot chat error:', error);
      return {
        success: false,
        response: 'I encountered an error processing your request. Please try again.',
        error: error.message,
      };
    }
  }
}
