import { Body, Controller, Get, Patch, SetMetadata, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
import { SystemConfigService } from './system-config.service';
import { UpdateSystemConfigDto } from './system-config.dto';
import { IamGuard } from '../../common/iam-adapter';
import { Roles } from '../../common/roles.decorator';

@ApiTags('Config')
@Controller('config')
export class SystemConfigController {
  constructor(private service: SystemConfigService) {}

  @Get('fayda-status')
  @SetMetadata('isPublic', true)
  @ApiOperation({ summary: 'Get Fayda verification enabled status (public)' })
  getFaydaStatus() {
    const enabled = process.env.VERIFAYDA_ENABLED !== 'false';
    return { enabled };
  }

  @Get()
  @ApiBearerAuth('IAM-auth')
  @UseGuards(IamGuard)
  @Roles('ADMIN')
  @ApiOperation({ summary: 'Get all system config (admin)' })
  getAll() {
    return this.service.getAll();
  }

  @Patch()
  @ApiBearerAuth('IAM-auth')
  @UseGuards(IamGuard)
  @Roles('ADMIN')
  @ApiOperation({ summary: 'Update system config (admin)' })
  update(@Body() dto: UpdateSystemConfigDto) {
    // The DTO validates/coerces each known key to a positive integer; persist back as strings.
    const entries: Record<string, string> = {};
    for (const [key, value] of Object.entries(dto)) {
      if (value !== undefined) entries[key] = String(value);
    }
    return this.service.updateMany(entries);
  }
}
