import {
  Controller,
  DefaultValuePipe,
  Get,
  Param,
  ParseIntPipe,
  Post,
  Query,
  UseGuards,
} from '@nestjs/common';
import {
  ApiBearerAuth,
  ApiOperation,
  ApiQuery,
  ApiTags,
} from '@nestjs/swagger';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { SyncService } from './sync.service';
import { SyncLogDto } from './dto/sync-log.dto';

@ApiTags('sync')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Controller('sync')
export class SyncController {
  constructor(private readonly service: SyncService) {}

  @Post('categories')
  @ApiOperation({ summary: 'Manually trigger category sync (async)' })
  async syncCategories() {
    return this.service.startCategorySync();
  }

  @Post('products')
  @ApiOperation({ summary: 'Manually trigger product sync (async)' })
  async syncProducts() {
    return this.service.startProductSync();
  }

  @Post('product-details')
  @ApiOperation({ summary: 'Manually sync details for all active origin products (async)' })
  async syncProductDetails() {
    return this.service.startProductDetailSync();
  }

  @Post('products/:goodId/detail')
  @ApiOperation({ summary: 'Immediately sync one SDS product detail' })
  async syncOneProductDetail(@Param('goodId') goodId: string) {
    return this.service.syncOneProductDetail(goodId);
  }

  @Get('status')
  @ApiOperation({ summary: 'Recent sync log entries' })
  @ApiQuery({ name: 'limit', required: false, type: Number })
  async status(
    @Query('limit', new DefaultValuePipe(20), ParseIntPipe) limit: number,
  ): Promise<SyncLogDto[]> {
    const logs = await this.service.getStatus(limit);
    return logs.map((l) => SyncLogDto.from(l));
  }
}
