import {
  Body,
  Controller,
  Get,
  Param,
  Post,
  UseGuards,
  UseInterceptors,
  UsePipes,
  ValidationPipe,
} from '@nestjs/common';
import { LicenseService } from './license.service';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import {
  ApiOkResponseListWithTotal,
  ApiResultListWithTotal,
} from '../common/types/api-result';
import { AcceptSyncDTO, ProjectLicenseTariffDTO } from './dto/license-dto';
import {
  RequestProjectAccess,
  ProjectAccess,
  ProjectAccessInterceptor,
} from '../utils/project-access';
import { OptTokenOrJwtAuthGuard } from '../guards/opt-token-or-jwt.auth.guard';

@ApiTags('license')
@Controller('license')
@UseGuards(OptTokenOrJwtAuthGuard)
@ApiBearerAuth()
export class LicenseController {
  constructor(private readonly licenseService: LicenseService) {}

  @Get('tariffs')
  @ApiOperation({
    summary: 'Get available tariffs',
  })
  @ApiOkResponseListWithTotal(ProjectLicenseTariffDTO)
  @UsePipes(
    new ValidationPipe({
      transform: true,
      transformOptions: { enableImplicitConversion: true },
    }),
  )
  async getTariffs(): Promise<ApiResultListWithTotal<ProjectLicenseTariffDTO>> {
    return await this.licenseService.getTariffs();
  }

  @Get('trial')
  @ApiOperation({
    summary: 'Get available tariffs',
  })
  @UsePipes(
    new ValidationPipe({
      transform: true,
      transformOptions: { enableImplicitConversion: true },
    }),
  )
  @UseInterceptors(ProjectAccessInterceptor)
  async isTrial(
    @RequestProjectAccess() projectAccess: ProjectAccess,
  ): Promise<boolean> {
    return await this.licenseService.isTrial(projectAccess.projectId);
  }

  @Post('trial')
  @ApiOperation({
    summary: 'Activate trial',
  })
  @UseInterceptors(ProjectAccessInterceptor)
  async createAsset(
    @RequestProjectAccess() projectAccess: ProjectAccess,
  ): Promise<boolean> {
    return await this.licenseService.activateTrial(projectAccess.projectId);
  }

  @Post('acceptSync')
  @ApiOperation({
    summary: 'Sync license',
  })
  @UsePipes(
    new ValidationPipe({
      transform: true,
      transformOptions: { enableImplicitConversion: true },
    }),
  )
  async acceptSync(@Body() params: AcceptSyncDTO): Promise<void> {
    this.licenseService._checkKey(params.key);
    return await this.licenseService.acceptSync(
      params.licenseTypes,
      params.projectLicenses,
    );
  }
}
