import {
  Controller,
  Post,
  Get,
  Put,
  Param,
  Body,
  ParseUUIDPipe,
  UseGuards,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiBearerAuth,
  ApiParam,
} from '@nestjs/swagger';
import { CurrentUser, JwtPayload } from '../common/decorators';
import { TenantGuard } from '../auth/guards/tenant.guard';
import { singleResponse } from '../common/dto/pagination.dto';
import { EnrichmentService } from './enrichment.service';
import { UpdateNorthDataSettingsDto } from './dto/enrichment-settings.dto';

@ApiTags('Datenanreicherung (Enrichment)')
@ApiBearerAuth('access-token')
@UseGuards(TenantGuard)
@Controller()
export class EnrichmentController {
  constructor(private readonly enrichmentService: EnrichmentService) {}

  @Post('companies/:id/enrich')
  @ApiOperation({
    summary: 'Unternehmensdaten anreichern (Vorschlaege, kein Auto-Write)',
  })
  @ApiParam({ name: 'id', type: 'string', format: 'uuid' })
  async enrich(
    @CurrentUser() user: JwtPayload,
    @Param('id', ParseUUIDPipe) id: string,
  ) {
    const result = await this.enrichmentService.enrichCompany(
      user.tenantId!,
      id,
    );
    return singleResponse(result);
  }

  @Get('settings/integrations/north-data')
  @ApiOperation({ summary: 'North Data Einstellungen abrufen' })
  async getSettings(@CurrentUser() user: JwtPayload) {
    const settings = await this.enrichmentService.getNorthDataSettings(
      user.tenantId!,
    );
    return singleResponse({
      ...settings,
      apiKey: settings.apiKey
        ? `****${settings.apiKey.slice(-4)}`
        : null,
    });
  }

  @Put('settings/integrations/north-data')
  @ApiOperation({ summary: 'North Data Einstellungen aktualisieren' })
  async updateSettings(
    @CurrentUser() user: JwtPayload,
    @Body() dto: UpdateNorthDataSettingsDto,
  ) {
    const settings = await this.enrichmentService.updateNorthDataSettings(
      user.tenantId!,
      dto,
    );
    return singleResponse({
      ...settings,
      apiKey: settings.apiKey
        ? `****${settings.apiKey.slice(-4)}`
        : null,
    });
  }
}
