import { Controller, Get, Post, Put, Delete, Body, Param, NotFoundException } from '@nestjs/common';
import { ContactRepository } from '../../../infrastructure/repositories/contact.repository';
import { Contact } from '../../../domain/entities/contact.entity';
import * as crypto from 'crypto';

@Controller('api/v1/comm/contacts')
export class ContactController {
  constructor(private readonly contactRepository: ContactRepository) {}

  @Get()
  async listContacts() {
    return this.contactRepository.findAll();
  }

  @Post()
  async createContact(@Body() body: any) {
    const contact = new Contact();
    contact.id = crypto.randomUUID();
    contact.tenantId = body.tenantId;
    contact.userId = body.userId;
    contact.name = body.name;
    contact.phone = body.phone;
    contact.email = body.email;
    contact.telegramId = body.telegramId;
    contact.wechatId = body.wechatId;
    contact.preferredChannel = body.preferredChannel;
    contact.isActive = body.isActive ?? true;
    return this.contactRepository.save(contact);
  }

  @Put(':id')
  async updateContact(@Param('id') id: string, @Body() body: any) {
    const contact = await this.contactRepository.findById(id);
    if (!contact) {
      throw new NotFoundException(`Contact ${id} not found`);
    }
    Object.assign(contact, body);
    return this.contactRepository.save(contact);
  }

  @Delete(':id')
  async deleteContact(@Param('id') id: string) {
    const contact = await this.contactRepository.findById(id);
    if (!contact) {
      throw new NotFoundException(`Contact ${id} not found`);
    }
    await this.contactRepository.remove(contact);
    return { message: 'Contact deleted', id };
  }
}
