import { Body, Controller, Get, Param, Post, Res } from '@nestjs/common';
import { Response } from 'express';
import { ApiTags } from '@nestjs/swagger';
import { Public } from 'src/core/guards';
import { GateScanEntity } from '../domain/entity/gate-request.entity';
import {
  GateMasterEntity,
  GateResponseEntity,
} from '../domain/entity/gate-response.entity';
import { Gate } from 'src/core/response';
import { GateLogDto } from './dto/logs.dto';

const masterGates = [
  '319b6d3e-b661-4d19-8695-0dd6fb76465e',
  '9afdb79d-7162-43e6-8ac6-f1941adea7ba',
  '7e4c0281-8cf2-420e-aba1-c8ff834de450',
  '19318ac8-caa0-47e4-8a41-2aac238d3665',
  '495bc25f-42c4-4007-8e79-3747fa1054b6',
  'b90fc9a9-efd9-4216-a8af-7ed120b141de',
  '4399e93c-a839-4802-a49d-f933c72b1433',
  '970673a7-6370-444a-931a-9784220dd35d',
  '151ab50e-4e54-4252-b3ab-f5c0817b27a0',
  '4c0e6924-baf5-47fb-a15b-fd1cd0958cc0',
];

const failedGates = [
  'b3c3ae7b-daf5-4340-998b-ee35ed41323d',
  'be157609-92b8-4989-920d-a81769bcb05a',
];

const gateResponses = [
  {
    statusCode: 200,
    code: 1,
    message: 'Berhasil Check In',
  },
  {
    statusCode: 403,
    code: 2,
    message: 'Gagal melakukan Check In. Karena tiket telah kadaluarsa',
  },
  {
    statusCode: 403,
    code: 3,
    message: 'Gagal melakukan Check In. Tiket tidak tersedia',
  },
];

@ApiTags(`Gate - read`)
@Controller(`v1/gate`)
@Public(true)
@Gate()
export class GateController {
  @Post('scan')
  async scan(
    @Body() data: GateScanEntity,
    @Res({ passthrough: true }) res: Response,
  ): Promise<GateResponseEntity> {
    console.log(data);
    if (masterGates.includes(data.uuid)) {
      res.status(200);
      return gateResponses[0];
    }
    if (failedGates.includes(data.uuid)) {
      res.status(403);
      return gateResponses[2];
    }

    const response = Math.floor(Math.random() * 3);
    const responseValue = gateResponses[response];

    res.status(responseValue.statusCode);
    return responseValue;
  }

  @Post('logs')
  async logs(@Body() data: GateLogDto): Promise<GateResponseEntity> {
    console.log(data);

    return { code: 1, message: 'success' };
  }

  @Get(':id/master')
  async detail(@Param('id') id: string): Promise<GateMasterEntity> {
    if (id == '1') return { codes: masterGates };
    return {
      codes: this.createRandomStringArray(masterGates),
    };
  }

  createRandomStringArray(inputArray: string[]): string[] {
    const randomLength = Math.floor(Math.random() * 4) + 2; // Random length between 2 and 5
    const outputArray: string[] = [];

    while (outputArray.length < randomLength) {
      const randomIndex = Math.floor(Math.random() * inputArray.length);
      outputArray.push(inputArray[randomIndex]);
    }

    return outputArray;
  }
}
