import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  Query,
  HttpCode,
  HttpStatus,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiBearerAuth,
  ApiParam,
} from '@nestjs/swagger';
import { CredentialsService } from './credentials.service';
import { CreateCredentialDto } from './dto/create-credential.dto';
import { UpdateCredentialDto } from './dto/update-credential.dto';
import { QueryCredentialsDto } from './dto/query-credentials.dto';
import { Roles } from '../../../auth/decorators/roles.decorator';
import { RequirePermissions } from '../../../auth/permissions/permissions.decorator';
import { Permission } from '../../../auth/permissions/permissions.enum';
import { CurrentUser } from '../../../auth/decorators/current-user.decorator';
import { JwtPayload } from '../../../auth/interfaces/jwt-payload.interface';
import { AuditLog } from '../../audit/audit.interceptor';

@ApiTags('integrations/credentials')
@ApiBearerAuth('JWT-auth')
@Controller('integrations/credentials')
export class CredentialsController {
  constructor(private readonly credentialsService: CredentialsService) {}

  @Post()
  @Roles('admin')
  @RequirePermissions(Permission.INTEGRATIONS_MANAGE)
  @AuditLog('IntegrationCredential', 'CREATE')
  @ApiOperation({ summary: 'Create a new integration credential' })
  @ApiResponse({
    status: 201,
    description: 'Credential created successfully',
  })
  @ApiResponse({ status: 400, description: 'Bad request - invalid data' })
  @ApiResponse({ status: 401, description: 'Unauthorized' })
  @ApiResponse({ status: 403, description: 'Forbidden - insufficient permissions' })
  @ApiResponse({
    status: 409,
    description: 'Conflict - credential with same name/type already exists',
  })
  create(
    @Body() createDto: CreateCredentialDto,
    @CurrentUser() user: JwtPayload,
  ) {
    return this.credentialsService.create(createDto, user.sub);
  }

  @Get()
  @RequirePermissions(Permission.INTEGRATIONS_VIEW)
  @ApiOperation({
    summary: 'Get all integration credentials (without decrypted secrets)',
  })
  @ApiResponse({
    status: 200,
    description: 'List of credentials with pagination',
  })
  @ApiResponse({ status: 401, description: 'Unauthorized' })
  findAll(@Query() query: QueryCredentialsDto) {
    return this.credentialsService.findAll(query);
  }

  @Get(':id')
  @RequirePermissions(Permission.INTEGRATIONS_MANAGE)
  @ApiOperation({
    summary: 'Get a single credential by ID (includes decrypted secrets)',
  })
  @ApiParam({ name: 'id', description: 'Credential ID' })
  @ApiResponse({
    status: 200,
    description: 'Credential details with decrypted secrets',
  })
  @ApiResponse({ status: 401, description: 'Unauthorized' })
  @ApiResponse({ status: 403, description: 'Forbidden - insufficient permissions' })
  @ApiResponse({ status: 404, description: 'Credential not found' })
  findOne(@Param('id') id: string) {
    return this.credentialsService.findOne(id);
  }

  @Put(':id')
  @Roles('admin')
  @RequirePermissions(Permission.INTEGRATIONS_MANAGE)
  @AuditLog('IntegrationCredential', 'UPDATE')
  @ApiOperation({ summary: 'Update an integration credential' })
  @ApiParam({ name: 'id', description: 'Credential ID' })
  @ApiResponse({
    status: 200,
    description: 'Credential updated successfully',
  })
  @ApiResponse({ status: 400, description: 'Bad request - invalid data' })
  @ApiResponse({ status: 401, description: 'Unauthorized' })
  @ApiResponse({ status: 403, description: 'Forbidden - insufficient permissions' })
  @ApiResponse({ status: 404, description: 'Credential not found' })
  @ApiResponse({
    status: 409,
    description: 'Conflict - credential with same name already exists',
  })
  update(
    @Param('id') id: string,
    @Body() updateDto: UpdateCredentialDto,
    @CurrentUser() user: JwtPayload,
  ) {
    return this.credentialsService.update(id, updateDto, user.sub);
  }

  @Delete(':id')
  @Roles('admin')
  @RequirePermissions(Permission.INTEGRATIONS_MANAGE)
  @AuditLog('IntegrationCredential', 'DELETE')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Deactivate an integration credential (soft delete)' })
  @ApiParam({ name: 'id', description: 'Credential ID' })
  @ApiResponse({
    status: 200,
    description: 'Credential deactivated successfully',
  })
  @ApiResponse({ status: 401, description: 'Unauthorized' })
  @ApiResponse({ status: 403, description: 'Forbidden - insufficient permissions' })
  @ApiResponse({ status: 404, description: 'Credential not found' })
  remove(@Param('id') id: string, @CurrentUser() user: JwtPayload) {
    return this.credentialsService.remove(id, user.sub);
  }

  @Post(':id/test')
  @RequirePermissions(Permission.INTEGRATIONS_MANAGE)
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Test connection with the credential' })
  @ApiParam({ name: 'id', description: 'Credential ID' })
  @ApiResponse({
    status: 200,
    description: 'Connection test result',
    schema: {
      type: 'object',
      properties: {
        success: { type: 'boolean' },
        message: { type: 'string' },
        latency: { type: 'number', description: 'Latency in milliseconds' },
      },
    },
  })
  @ApiResponse({ status: 401, description: 'Unauthorized' })
  @ApiResponse({ status: 403, description: 'Forbidden - insufficient permissions' })
  @ApiResponse({ status: 404, description: 'Credential not found' })
  testConnection(@Param('id') id: string) {
    return this.credentialsService.testConnection(id);
  }
}
