import { Controller, Get, Post, Body, Query } from '@nestjs/common';
import { MessageRepository } from '../../../infrastructure/repositories/message.repository';
import { Message } from '../../../domain/entities/message.entity';
import * as crypto from 'crypto';

@Controller('api/v1/comm/messages')
export class MessageController {
  constructor(private readonly messageRepository: MessageRepository) {}

  @Get()
  async listMessages(@Query('direction') direction?: string) {
    if (direction) {
      return this.messageRepository.findByDirection(direction);
    }
    return this.messageRepository.findAll();
  }

  @Post()
  async sendMessage(@Body() body: any) {
    const message = new Message();
    message.id = crypto.randomUUID();
    message.tenantId = body.tenantId;
    message.contactId = body.contactId;
    message.channelType = body.channelType;
    message.direction = body.direction ?? 'outbound';
    message.content = body.content;
    message.priority = body.priority ?? 'normal';
    message.deliveryStatus = 'pending';
    message.relatedTaskId = body.relatedTaskId;
    message.createdAt = new Date();
    return this.messageRepository.save(message);
  }
}
