import { Controller, Get, Post, Patch, Param, Body, Query, Delete, Put } from '@nestjs/common'
import { EmailService } from './email.service'
import { RegisterEmailAccountDto, ConfirmAssociationDto, SendEmailDto } from './dto/email.dto'

@Controller('email')
export class EmailController {
  constructor(private readonly service: EmailService) {}

  // ── Emails ────────────────────────────────────────────────────────────────

  @Get()
  findAll(
    @Query('clientFolderId')   clientFolderId?:   string,
    @Query('matterId')         matterId?:         string,
    @Query('direction')        direction?:        string,
    @Query('associationStatus') associationStatus?: string,
    @Query('unreadOnly')       unreadOnly?:       string,
    @Query('limit')            limit?:            string,
    @Query('offset')           offset?:           string,
  ) {
    return this.service.findAll({
      clientFolderId,
      matterId,
      direction,
      associationStatus,
      unreadOnly: unreadOnly === 'true',
      limit:  limit  ? parseInt(limit)  : undefined,
      offset: offset ? parseInt(offset) : undefined,
    })
  }

  @Get('pending-count')
  pendingCount() {
    return this.service.pendingCount()
  }

  @Get('thread/:threadId')
  findThread(@Param('threadId') threadId: string) {
    return this.service.findThread(threadId)
  }

  // ── Server settings — must be before :id to avoid route conflict ──────────

  @Get('settings')
  getSettings() {
    return this.service.getSettings()
  }

  @Put('settings')
  saveSettings(@Body() body: Record<string, any>) {
    return this.service.saveSettings(body)
  }

  @Post('test-settings')
  testSettings(@Body() body: Record<string, any>) {
    return this.service.testSettings(body)
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.service.findOne(id)
  }

  @Post('send')
  send(@Body() dto: SendEmailDto) {
    return this.service.sendEmail(dto)
  }

  @Patch(':id/read')
  markRead(@Param('id') id: string) {
    return this.service.markRead(id)
  }

  @Patch(':id/archive')
  markArchived(@Param('id') id: string) {
    return this.service.markArchived(id)
  }

  @Patch(':id/associate')
  confirmAssociation(
    @Param('id') id: string,
    @Body() dto: ConfirmAssociationDto,
  ) {
    return this.service.confirmAssociation(id, dto)
  }

  // ── User email accounts ───────────────────────────────────────────────────

  @Get('accounts/list')
  listAccounts() {
    return this.service.listAccounts()
  }

  @Post('accounts')
  registerAccount(@Body() dto: RegisterEmailAccountDto) {
    return this.service.registerAccount(dto)
  }

  @Delete('accounts/:id')
  removeAccount(@Param('id') id: string) {
    return this.service.removeAccount(id)
  }

}
