import {
  Body,
  Controller,
  FileTypeValidator,
  Get,
  HttpException,
  Param,
  ParseFilePipe,
  Post,
  Query,
  UploadedFile,
  UseInterceptors,

} from "@nestjs/common";
import { FileInterceptor } from "@nestjs/platform-express";
import { AnalyticsReportService } from "./AnalyticsReport.service";
import * as moment from "moment";
import { Cron } from '@nestjs/schedule';
import { CronSyncService } from "./CronSyncService.service";
import { recordTypeEnum } from "src/models/AnalyticsReport.schema";

@Controller("asr")
export class AnalyticsReportController {
  constructor(
    private readonly analyticsService: AnalyticsReportService,
    private readonly CronSyncService: CronSyncService,
  ) { }

  // user signup
  @Get("/sync/download")
  async SyncDownloadReports() {
    try {
      return this.CronSyncService.doSyncAnalyticsReport(recordTypeEnum.DOWNLOAD, null)
    } catch (error) {
      throw new HttpException(error, 400);
    }
  }

  @Get("/list")
  async allVendor() {
    try {
      return this.analyticsService.doGetVendorList()
    } catch (error) {
      throw new HttpException(error, 400);
    }
  }

  @Get("/sync/sales")
  async SyncSalesReports() {
    try {
      return this.CronSyncService.doSyncAnalyticsReport(recordTypeEnum.SALES, null)
    } catch (error) {
      throw new HttpException(error, 400);
    }
  }

  @Get("/sync/healthcheal")
  async Synchealth() {
    try {
      return this.CronSyncService.doSyncHealth()
    } catch (error) {
      throw new HttpException(error, 400);
    }
  }

  // @Cron('30 5 * * *')
  @Post('sync/apps')
  @UseInterceptors(FileInterceptor('AppFile'))
  async SyncCredentials(@UploadedFile(
    new ParseFilePipe({
      validators: [new FileTypeValidator({ fileType: '.csv' })],
      fileIsRequired: true,
    }),
  ) file: Express.Multer.File) {
    return await this.CronSyncService.doHandleAccountsSyncing(file)
  }

  @Get('sync/apps')
  async doFetchCredentials() {
    return await this.CronSyncService.doFetchVendors()
  }

  @Get("/sync/b/:type")
  async SyncSalesReportsBatch(@Param() { type }, @Query() { from, to }) {
    try {
      const isDateValid = (date) => moment(date, "DD-MM-YYYY").isValid() && date?.length == 10
      if (isDateValid(from) == false) {
        return {
          status: false,
          code: 422,
          message: "From is not invalid format!"
        }
      }
      if (isDateValid(to) == false) {
        return {
          status: false,
          code: 422,
          message: "To is not invalid format!"
        }
      }
      if (type !== recordTypeEnum.DOWNLOAD.toLowerCase() && type !== recordTypeEnum.SALES.toLowerCase()) {
        return {
          status: false,
          code: 422,
          message: "Type is not valid!"
        }
      }
      // return this.CronSyncService.doSyncReportInBatch(from,to,type.toUpperCase())
      //@ts-ignore
      return this.CronSyncService.doSyncReportInBatch(from, to, type.toUpperCase())
    } catch (error) {
      throw new HttpException(error, 400);
    }
  }

  @Get("/token")
  async doGetJWTTOken() {
    try {
      return this.analyticsService.generateJWT()
    } catch (error) {
      throw new HttpException(error, 400);
    }
  }
  @Get("/country")
  async country() {
    try {
      return this.analyticsService.doHandleParsingCSV()
    } catch (error) {
      throw new HttpException(error, 400);
    }
  }
  // get latest currency value
  @Get("/sync/exchange-rate")
  async SyncExchangeRate() {
    try {
      return await this.CronSyncService.doSyncCountryWisevaluation()
    } catch (error) {
      throw new HttpException(error, 400);
    }
  }
  @Post("/analytics")
  async GetAnalytics(@Body() body) {
    try {
      let { type, from, to, AccountID } = body;
      if (!AccountID || AccountID.length === 0) {
        return {
          status: false,
          code: 422,
          message: "AccountID is rquired!"
        }
      }
      const isDateValid = (date) => moment(date, "DD-MM-YYYY").isValid() && date?.length == 10
      if (isDateValid(from) == false) {
        return {
          status: false,
          code: 422,
          message: "From is not invalid format!"
        }
      }
      if (isDateValid(to) == false) {
        return {
          status: false,
          code: 422,
          message: "To is not invalid format!"
        }
      }
      // if (type !== recordTypeEnum.DOWNLOAD.toLowerCase() && type !== recordTypeEnum.SALES.toLowerCase()) {
      //   return {
      //     status: false,
      //     code: 422,
      //     message: "Type is not valid!"
      //   }
      // }
      // return await this.analyticsService.doGetAnalyticsForDate(from, to, type, AccountID);
      return await this.analyticsService.analysticsData(from, to, recordTypeEnum, AccountID);
      // let record = await this.analyticsService.doGetAnalyticsForDate(body);
      // return await encryptionInterceptor(record)

    } catch (error) {
      console.log(error)
      throw new HttpException(error, 400);
    }
  }


  @Post('/merge')
  async mergeAnalyticsData(@Body() body) {
    try {
      let { from, to, AccountID } = body;
      return await this.analyticsService.mergeAnalyticsData(from, to, AccountID);
    } catch (error) {
      console.log(error, 'error');
    }
  }

  @Get('/iconList/:id')
  async storeIcon(@Param('id') id: string) {
    try {
      return await this.analyticsService.doStoreICon(id)
    } catch (error) {
      console.log(error, 'error');
    }
  }
}
