import {
  Controller,
  Post,
  Get,
  Delete,
  Patch,
  Body,
  Param,
  Req,
} from '@nestjs/common';
import { AIService } from './ai.service';
import { ChatMessageDto } from './dto/chat-message.dto';
import { Public } from '../auth/decorators/public.decorator';

@Controller('api/v1/ai')
export class AIController {
  constructor(private readonly aiService: AIService) {}

  @Public() // Public for testing
  @Post('chat')
  async chat(@Req() req: any, @Body() chatDto: ChatMessageDto) {
    const userId = req.user?.userId || 'test_user_123'; // Use test user if not authenticated
    const response = await this.aiService.chat(userId, chatDto);
    return {
      success: true,
      data: response,
    };
  }

  @Public() // Public for testing
  @Get('conversations')
  async getConversations(@Req() req: any) {
    const userId = req.user?.userId || 'test_user_123';
    const conversations = await this.aiService.getUserConversations(userId);
    return {
      success: true,
      data: { conversations },
    };
  }

  @Public() // Public for testing
  @Get('conversations/:id')
  async getConversation(@Req() req: any, @Param('id') conversationId: string) {
    const userId = req.user?.userId || 'test_user_123';
    const conversation = await this.aiService.getConversation(
      userId,
      conversationId,
    );
    return {
      success: true,
      data: { conversation },
    };
  }

  @Delete('conversations/:id')
  async deleteConversation(
    @Req() req: any,
    @Param('id') conversationId: string,
  ) {
    await this.aiService.deleteConversation(req.user.userId, conversationId);
    return {
      success: true,
      message: 'Conversation deleted successfully',
    };
  }

  @Public() // Public for testing
  @Patch('conversations/:id/group')
  async updateConversationGroup(
    @Req() req: any,
    @Param('id') conversationId: string,
    @Body() body: { groupName: string | null },
  ) {
    const userId = req.user?.userId || 'test_user_123';
    const conversation = await this.aiService.updateConversationGroup(
      userId,
      conversationId,
      body.groupName,
    );
    return {
      success: true,
      data: { conversation },
    };
  }

  @Public() // Public for testing
  @Get('groups')
  async getConversationGroups(@Req() req: any) {
    const userId = req.user?.userId || 'test_user_123';
    const groups = await this.aiService.getConversationGroups(userId);
    return {
      success: true,
      data: { groups },
    };
  }

  @Public() // Public for testing
  @Get('provider-status')
  async getProviderStatus() {
    const status = this.aiService.getProviderStatus();
    return {
      success: true,
      data: status,
    };
  }

  // Embeddings testing endpoints
  @Public() // Public for testing
  @Post('test/embeddings/generate')
  async testGenerateEmbedding(@Body() body: { text: string }) {
    const embeddingsService = this.aiService['embeddingsService'];
    const result = await embeddingsService.generateEmbedding(body.text);
    return {
      success: true,
      data: {
        dimensions: result.embedding.length,
        tokenCount: result.tokenCount,
        model: result.model,
        preview: result.embedding.slice(0, 5), // First 5 dimensions
      },
    };
  }

  @Public() // Public for testing
  @Post('test/embeddings/search')
  async testSearchSimilar(
    @Body()
    body: {
      query: string;
      userId?: string;
      threshold?: number;
      limit?: number;
    },
  ) {
    const embeddingsService = this.aiService['embeddingsService'];
    const userId = body.userId || 'test_user_123';
    const results = await embeddingsService.searchSimilarConversations(
      body.query,
      userId,
      {
        similarityThreshold: body.threshold || 0.7,
        limit: body.limit || 5,
      },
    );
    return {
      success: true,
      data: { results },
    };
  }

  @Public() // Public for testing
  @Get('test/embeddings/health')
  async testEmbeddingsHealth() {
    const embeddingsService = this.aiService['embeddingsService'];
    const health = await embeddingsService.healthCheck();
    return {
      success: true,
      data: health,
    };
  }

  @Public() // Public for testing
  @Get('test/embeddings/stats/:userId')
  async testEmbeddingsStats(@Param('userId') userId: string) {
    const embeddingsService = this.aiService['embeddingsService'];
    const stats = await embeddingsService.getUserEmbeddingStats(
      userId || 'test_user_123',
    );
    return {
      success: true,
      data: stats,
    };
  }
}
