import {
  Controller,
  Get,
  Post,
  Delete,
  Body,
  Param,
  UseGuards,
} 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 { SignalService, SignalStatus } from './signal.service';

@Controller('signal')
@UseGuards(JwtAuthGuard, RolesGuard)
export class SignalController {
  constructor(private readonly signalService: SignalService) {}

  /**
   * Get Signal connection status
   */
  @Get('status')
  @Roles('ADMINISTRATOR')
  async getStatus(): Promise<SignalStatus> {
    return this.signalService.getStatus();
  }

  /**
   * Get QR code for linking device
   */
  @Get('qrcode')
  @Roles('ADMINISTRATOR')
  async getQRCode() {
    const result = await this.signalService.getQRCodeLink();
    if (!result) {
      return {
        success: false,
        message: 'Device already linked. Unlink first to re-link.',
      };
    }
    return {
      success: true,
      qrcode: result.qrcode,
    };
  }

  /**
   * Register a new phone number
   */
  @Post('register')
  @Roles('ADMINISTRATOR')
  async registerNumber(@Body() body: { phoneNumber: string; captcha?: string }) {
    return this.signalService.registerNumber(body.phoneNumber, body.captcha);
  }

  /**
   * Verify phone number with code
   */
  @Post('verify')
  @Roles('ADMINISTRATOR')
  async verifyNumber(@Body() body: { phoneNumber: string; code: string }) {
    return this.signalService.verifyNumber(body.phoneNumber, body.code);
  }

  /**
   * Unlink the current account
   */
  @Delete('unlink/:phoneNumber')
  @Roles('ADMINISTRATOR')
  async unlinkAccount(@Param('phoneNumber') phoneNumber: string) {
    return this.signalService.unlinkAccount(phoneNumber);
  }

  /**
   * Send a test message
   */
  @Post('send')
  @Roles('ADMINISTRATOR')
  async sendMessage(@Body() body: { to: string; message: string }) {
    const fromNumber = await this.signalService.getLinkedNumber();
    if (!fromNumber) {
      return {
        success: false,
        error: 'No Signal account linked. Please link an account first.',
      };
    }

    const formattedTo = this.signalService.formatPhoneNumber(body.to);
    return this.signalService.sendMessage(fromNumber, formattedTo, body.message);
  }

  /**
   * Send message to multiple recipients
   */
  @Post('send-bulk')
  @Roles('ADMINISTRATOR', 'COORDINATOR')
  async sendBulkMessage(@Body() body: { recipients: string[]; message: string }) {
    const fromNumber = await this.signalService.getLinkedNumber();
    if (!fromNumber) {
      return {
        success: false,
        error: 'No Signal account linked. Please link an account first.',
      };
    }

    const formattedRecipients = body.recipients.map((r) =>
      this.signalService.formatPhoneNumber(r),
    );
    return this.signalService.sendBulkMessage(
      fromNumber,
      formattedRecipients,
      body.message,
    );
  }

  /**
   * Send a PDF or file attachment via Signal
   */
  @Post('send-attachment')
  @Roles('ADMINISTRATOR', 'COORDINATOR')
  async sendAttachment(
    @Body()
    body: {
      to: string;
      message?: string;
      attachment: string; // Base64 encoded file
      filename: string;
      mimeType?: string;
    },
  ) {
    const fromNumber = await this.signalService.getLinkedNumber();
    if (!fromNumber) {
      return {
        success: false,
        error: 'No Signal account linked. Please link an account first.',
      };
    }

    const formattedTo = this.signalService.formatPhoneNumber(body.to);
    return this.signalService.sendMessageWithAttachment(
      fromNumber,
      formattedTo,
      body.message || '',
      body.attachment,
      body.filename,
      body.mimeType || 'application/pdf',
    );
  }
}
