import {
  Body,
  Controller,
  Get,
  Patch,
  Path,
  Post,
  Request,
  Route,
  Security,
  Tags,
} from "tsoa";
import { AppDataSource } from "../database/data-source";
import { In } from "typeorm";
import {
  ProfileEmployeeAbsentLate,
  CreateProfileEmployeeAbsentLate,
  CreateProfileEmployeeAbsentLateBatch,
  UpdateProfileEmployeeAbsentLate,
} from "../entities/ProfileEmployeeAbsentLate";
import { ProfileEmployeeAbsentLateHistory } from "../entities/ProfileEmployeeAbsentLateHistory";
import HttpSuccess from "../interfaces/http-success";
import HttpStatus from "../interfaces/http-status";
import HttpError from "../interfaces/http-error";
import { RequestWithUser } from "../middlewares/user";
import { ProfileEmployee } from "../entities/ProfileEmployee";
import permission from "../interfaces/permission";
import { setLogDataDiff } from "../interfaces/utils";

@Route("api/v1/org/profile-employee/absent-late")
@Tags("ProfileEmployeeAbsentLate")
@Security("bearerAuth")
export class ProfileEmployeeAbsentLateController extends Controller {
  private profileRepo = AppDataSource.getRepository(ProfileEmployee);
  private absentLateRepo = AppDataSource.getRepository(ProfileEmployeeAbsentLate);
  private historyRepo = AppDataSource.getRepository(ProfileEmployeeAbsentLateHistory);

  /**
   * API ดึงข้อมูลการมาสาย/ขาดราชการของ user
   * @summary API ดึงข้อมูลการมาสาย/ขาดราชการของ user
   */
  @Get("user")
  public async getAbsentLateUser(@Request() request: { user: Record<string, any> }) {
    const profile = await this.profileRepo.findOneBy({ keycloak: request.user.sub });
    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }
    const record = await this.absentLateRepo.find({
      where: { profileEmployeeId: profile.id, isDeleted: false },
      order: { stampDate: "DESC" },
    });
    return new HttpSuccess(record);
  }

  /**
   * API ดึงข้อมูลการมาสาย/ขาดราชการตาม profileId
   * @summary API ดึงข้อมูลการมาสาย/ขาดราชการตาม profileId
   * @param profileId คีย์ profile
   */
  @Get("{profileId}")
  public async getAbsentLate(@Path() profileId: string, @Request() req: RequestWithUser) {
    let _workflow = await new permission().Workflow(req, profileId, "SYS_REGISTRY_EMP");
    if (_workflow == false)
      await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_EMP", profileId);
    const record = await this.absentLateRepo.find({
      where: { profileEmployeeId: profileId, isDeleted: false },
      order: { stampDate: "DESC" },
    });
    return new HttpSuccess(record);
  }

  /**
   * API สร้างข้อมูลการมาสาย/ขาดราชการ
   * @summary API สร้างข้อมูลการมาสาย/ขาดราชการ
   */
  @Post()
  public async newAbsentLate(
    @Request() req: RequestWithUser,
    @Body() body: CreateProfileEmployeeAbsentLate,
  ) {
    if (!body.profileEmployeeId) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileEmployeeId");
    }

    const profile = await this.profileRepo.findOneBy({ id: body.profileEmployeeId });
    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }
    await new permission().PermissionOrgUserUpdate(req, "SYS_REGISTRY_EMP", profile.id);

    const before = null;
    const data = new ProfileEmployeeAbsentLate();

    const meta = {
      createdUserId: req.user.sub,
      createdFullName: req.user.name,
      lastUpdateUserId: req.user.sub,
      lastUpdateFullName: req.user.name,
      createdAt: new Date(),
      lastUpdatedAt: new Date(),
    };

    Object.assign(data, { ...body, ...meta });

    // บันทึก history
    const history = new ProfileEmployeeAbsentLateHistory();
    Object.assign(history, { ...data, id: undefined });

    await this.absentLateRepo.save(data, { data: req });
    setLogDataDiff(req, { before, after: data });
    history.profileEmployeeAbsentLateId = data.id;
    await this.historyRepo.save(history, { data: req });

    return new HttpSuccess(data.id);
  }

  /**
   * API สร้างข้อมูลการมาสาย/ขาดราชการ (สำหรับ Job)
   * @summary API สร้างข้อมูลการมาสาย/ขาดราชการ (สำหรับ Job) 
   */
  @Post("batch")
  public async newAbsentLateBatch(
    @Request() req: RequestWithUser,
    @Body() body: CreateProfileEmployeeAbsentLateBatch,
  ) {
    // กรณีไม่มีข้อมูลส่งมา (วันที่ไม่มีคนขาด/มาสาย)
    if (!body.records || body.records.length === 0) {
      return new HttpSuccess({ count: 0, ids: [] });
    }

    const profileIds = [...new Set(body.records.map((r) => r.profileEmployeeId))];
    const profiles = await this.profileRepo.findBy({
      id: In(profileIds),
    });

    const foundProfileIds = new Set(profiles.map((p) => p.id));
    const validRecords = body.records.filter((r) => foundProfileIds.has(r.profileEmployeeId));

    // กรณีไม่พบ profile เลย
    if (validRecords.length === 0) {
      return new HttpSuccess({ count: 0, ids: [] });
    }

    const meta = {
      createdUserId: req.user.sub,
      createdFullName: req.user.name,
      lastUpdateUserId: req.user.sub,
      lastUpdateFullName: req.user.name,
      createdAt: new Date(),
      lastUpdatedAt: new Date(),
    };

    const records = validRecords.map((item) => {
      const data = new ProfileEmployeeAbsentLate();
      Object.assign(data, { ...item, ...meta });
      return data;
    });

    const result = await this.absentLateRepo.save(records, { data: req });

    // บันทึก history สำหรับแต่ละ record
    const historyRecords = result.map((data) => {
      const history = new ProfileEmployeeAbsentLateHistory();
      Object.assign(history, { ...data, id: undefined });
      history.profileEmployeeAbsentLateId = data.id;
      return history;
    });
    await this.historyRepo.save(historyRecords, { data: req });

    return new HttpSuccess({ count: result.length, ids: result.map((r) => r.id) });
  }

  /**
   * API แก้ไขข้อมูลการมาสาย/ขาดราชการ
   * @summary API แก้ไขข้อมูลการมาสาย/ขาดราชการ
   * @param absentLateId คีย์การมาสาย/ขาดราชการ
   */
  @Patch("{absentLateId}")
  public async editAbsentLate(
    @Request() req: RequestWithUser,
    @Body() body: UpdateProfileEmployeeAbsentLate,
    @Path() absentLateId: string,
  ) {
    const record = await this.absentLateRepo.findOneBy({ id: absentLateId });
    if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    await new permission().PermissionOrgUserUpdate(
      req,
      "SYS_REGISTRY_EMP",
      record.profileEmployeeId,
    );

    const before = structuredClone(record);
    const history = new ProfileEmployeeAbsentLateHistory();
    Object.assign(history, { ...record, id: undefined });

    Object.assign(record, body);
    Object.assign(history, { ...record, id: undefined });

    history.profileEmployeeAbsentLateId = absentLateId;
    record.lastUpdateUserId = req.user.sub;
    record.lastUpdateFullName = req.user.name;
    record.lastUpdatedAt = new Date();
    history.lastUpdateUserId = req.user.sub;
    history.lastUpdateFullName = req.user.name;
    history.createdUserId = req.user.sub;
    history.createdFullName = req.user.name;
    history.createdAt = new Date();
    history.lastUpdatedAt = new Date();

    await Promise.all([
      this.absentLateRepo.save(record, { data: req }),
      setLogDataDiff(req, { before, after: record }),
      this.historyRepo.save(history, { data: req }),
    ]);

    return new HttpSuccess();
  }

  /**
   * API ลบข้อมูลการมาสาย/ขาดราชการ (Soft Delete)
   * @summary API ลบข้อมูลการมาสาย/ขาดราชการ (Soft Delete)
   * @param absentLateId คีย์การมาสาย/ขาดราชการ
   */
  @Patch("update-delete/{absentLateId}")
  public async updateIsDeleted(
    @Request() req: RequestWithUser,
    @Path() absentLateId: string,
  ) {
    const record = await this.absentLateRepo.findOneBy({ id: absentLateId });
    if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    if (record.isDeleted === true) {
      return new HttpSuccess();
    }
    await new permission().PermissionOrgUserDelete(req, "SYS_REGISTRY_EMP", record.profileEmployeeId);

    const before = structuredClone(record);
    const history = new ProfileEmployeeAbsentLateHistory();
    Object.assign(history, { ...record, id: undefined });

    record.isDeleted = true;
    record.lastUpdateUserId = req.user.sub;
    record.lastUpdateFullName = req.user.name;
    record.lastUpdatedAt = new Date();

    history.profileEmployeeAbsentLateId = absentLateId;
    history.isDeleted = true;
    history.lastUpdateUserId = req.user.sub;
    history.lastUpdateFullName = req.user.name;
    history.lastUpdatedAt = new Date();

    await Promise.all([
      this.absentLateRepo.save(record, { data: req }),
      setLogDataDiff(req, { before, after: record }),
      this.historyRepo.save(history, { data: req }),
    ]);

    return new HttpSuccess();
  }

  /**
   * API ดึงประวัติการมาสาย/ขาดราชการ
   * @summary API ดึงประวัติการมาสาย/ขาดราชการ
   * @param absentLateId คีย์การมาสาย/ขาดราชการ
   */
  @Get("history/{absentLateId}")
  public async getHistory(@Path() absentLateId: string, @Request() req: RequestWithUser) {
    const record = await this.absentLateRepo.findOneBy({ id: absentLateId });
    if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_EMP", record.profileEmployeeId);

    const history = await this.historyRepo.find({
      where: { profileEmployeeAbsentLateId: absentLateId },
      order: { createdAt: "DESC" },
    });
    return new HttpSuccess(history);
  }
}
