import {
  Controller,
  Get,
  Post,
  Put,
  Body,
  Query,
  UseGuards,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiBearerAuth,
  ApiResponse,
} from '@nestjs/swagger';
import { IntegrationService } from './integration.service';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../auth/guards/roles.guard';
import { ModuleGuard } from '../../common/guards/module.guard';
import { Roles, UserRole } from '../../common/decorators/roles.decorator';
import { RequireModule } from '../../common/decorators/require-module.decorator';
import {
  CurrentUser,
  JwtPayload,
} from '../../common/decorators/current-user.decorator';
import {
  UpdateIntegrationConfigDto,
  FindSyncLogsDto,
  TriggerSyncDto,
} from './dto';

@ApiTags('Integration')
@ApiBearerAuth()
@Controller('integration')
@UseGuards(JwtAuthGuard, ModuleGuard, RolesGuard)
@RequireModule('1c_sync')
@Roles(UserRole.CLUB_ADMIN)
export class IntegrationController {
  constructor(private readonly integrationService: IntegrationService) {}

  @Get('config')
  @ApiOperation({ summary: 'Get integration configuration' })
  @ApiResponse({ status: 200, description: 'Integration config (API key masked)' })
  async getConfig(@CurrentUser() user: JwtPayload) {
    return this.integrationService.getConfig(user.clubId);
  }

  @Put('config')
  @ApiOperation({ summary: 'Create or update integration configuration' })
  @ApiResponse({ status: 200, description: 'Integration config saved' })
  async upsertConfig(
    @CurrentUser() user: JwtPayload,
    @Body() dto: UpdateIntegrationConfigDto,
  ) {
    return this.integrationService.upsertConfig(user.clubId, dto);
  }

  @Post('sync')
  @ApiOperation({ summary: 'Trigger a sync operation' })
  @ApiResponse({ status: 201, description: 'Sync operation queued' })
  @ApiResponse({ status: 400, description: 'Sync not enabled or not configured' })
  async triggerSync(
    @CurrentUser() user: JwtPayload,
    @Body() dto: TriggerSyncDto,
  ) {
    return this.integrationService.triggerSync(user.clubId, dto);
  }

  @Get('sync')
  @ApiOperation({ summary: 'Get sync log with pagination' })
  @ApiResponse({ status: 200, description: 'Paginated list of sync logs' })
  async findSyncLogs(
    @CurrentUser() user: JwtPayload,
    @Query() query: FindSyncLogsDto,
  ) {
    return this.integrationService.findSyncLogs(user.clubId, query);
  }
}
