import { Controller, Get, Query, Res, HttpException, HttpStatus, UseGuards, Header } from '@nestjs/common';
import { AbsenService } from './absen.service.js';
import { Response } from 'express';
import { ApiKeyGuard } from '../guards/api-key.guard.js';
import * as path from 'path';
import * as fs from 'fs';

@Controller('absen')
@UseGuards(ApiKeyGuard)
export class AbsenController {
  constructor(private readonly absenService: AbsenService) {}

  @Get('json')
  @Header('Content-Type', 'application/json; charset=utf-8')
  async getAbsenJson(
    @Query('lokasi') lokasi: string,
    @Query('month') monthStr: string,
    @Query('year') yearStr: string,
    @Query('page') pageStr: string,
    @Query('limit') limitStr: string,
  ) {
    if (!lokasi || !/^[a-zA-Z0-9_-]+$/.test(lokasi)) {
      throw new HttpException({ status: 'error', message: 'Format lokasi tidak valid atau kosong' }, HttpStatus.BAD_REQUEST);
    }

    const now = new Date();
    const month = monthStr ? parseInt(monthStr, 10) : (now.getMonth() + 1);
    const year = yearStr ? parseInt(yearStr, 10) : now.getFullYear();
    const page = pageStr ? parseInt(pageStr, 10) : 1;
    let limit = limitStr ? parseInt(limitStr, 10) : 5000;
    
    if (page < 1) throw new HttpException('Page must be >= 1', HttpStatus.BAD_REQUEST);
    if (limit < 1) limit = 5000;

    const offset = (page - 1) * limit;

    // Resolve MDB Path
    const targetFile = this.resolveMdbPath(lokasi);
    if (!fs.existsSync(targetFile)) {
      throw new HttpException({ status: 'error', message: `File database mdb tidak ditemukan untuk lokasi ${lokasi}` }, HttpStatus.NOT_FOUND);
    }

    // Call service to get data
    try {
      const response = await this.absenService.getAbsenData(targetFile, lokasi, month, year, page, limit, offset);
      return JSON.stringify(response, null, 2);
    } catch (error) {
      console.error(error);
      throw new HttpException({ status: 'error', message: 'Gagal koneksi atau query MDB: ' + ((error as any).message || error) }, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  @Get('download')
  downloadMdb(@Query('lokasi') lokasi: string, @Res() res: any) {
    if (!lokasi || !/^[a-zA-Z0-9_-]+$/.test(lokasi)) {
      throw new HttpException({ status: 'error', message: 'Format lokasi tidak valid atau kosong' }, HttpStatus.BAD_REQUEST);
    }

    const targetFile = this.resolveMdbPath(lokasi);
    if (!fs.existsSync(targetFile)) {
      throw new HttpException({ status: 'error', message: `File database mdb tidak ditemukan untuk lokasi ${lokasi}` }, HttpStatus.NOT_FOUND);
    }

    res.download(targetFile, 'att2000.mdb', (err: any) => {
      if (err) {
        if (!res.headersSent) {
          res.status(500).json({ status: 'error', message: 'Gagal mendownload file' });
        }
      }
    });
  }

  private resolveMdbPath(lokasi: string): string {
    // Langsung tembak ke lokasi database bawaan mesin absensi
    return 'C:\\Program Files (x86)\\Att\\att2000.mdb';
  }
}
