import { Controller, Post, Body, UseInterceptors, UploadedFile, BadRequestException, Get, Param, Delete, UseGuards } from '@nestjs/common';
import { PatientRecordsService } from './patient_records.service';
import { PatientRecord } from './entities/patient_record.entity';
import { FileInterceptor } from '@nestjs/platform-express';
import { S3, PutObjectCommand } from '@aws-sdk/client-s3';
import { awsConfig } from 'src/aws.config';
import { AuthGuard } from 'src/auth/auth.guard';

@Controller('patient_records')
export class PatientRecordsController {
  constructor(private readonly patientRecordsService: PatientRecordsService) {}
  @UseGuards(AuthGuard)
  @Post()
  @UseInterceptors(FileInterceptor('file'))
  async create(@UploadedFile() file: Express.Multer.File, @Body() recordEntity: PatientRecord) {
    console.log("file", file);
    console.log(recordEntity, "recordEntity");

    try {
      if (file) {
        const s3 = new S3({
          credentials: {
            accessKeyId: awsConfig.accessKeyId,
            secretAccessKey: awsConfig.secretAccessKey,
          },
          region: awsConfig.region,
        });

        const filname = `${file.originalname}_${Date.now()}`
        const command = new PutObjectCommand({
          Bucket: awsConfig.bucketName,
          Key: filname,
          Body: file.buffer,
        });

        const data = await s3.send(command);
        console.log(data, "data");

        recordEntity.files = filname;
        console.log("recordEntity.files", recordEntity.files);
      }

      return this.patientRecordsService.create(recordEntity, file);
    } catch (error) {
      console.error(error);
      throw new BadRequestException('Failed to upload file to S3');
    }
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    console.log("entering");
    return this.patientRecordsService.findOne(+id);
  }

  @Get(':id/:type_id')
  findByType(@Param('id') id: number, @Param('type_id') type_id: number) {
    return this.patientRecordsService.findByType(id, type_id);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.patientRecordsService.remove(+id);
  }
}
