import {
  Body,
  Controller,
  Delete,
  Get,
  Patch,
  Path,
  Post,
  Request,
  Route,
  Security,
  Tags,
} from "tsoa";
import { AppDataSource } from "../database/data-source";
import {
  ProfileLeaveHistory,
  CreateProfileLeave,
  ProfileLeave,
  UpdateProfileLeave,
} from "../entities/ProfileLeave";
import HttpSuccess from "../interfaces/http-success";
import HttpStatus from "../interfaces/http-status";
import HttpError from "../interfaces/http-error";
import { RequestWithUser } from "../middlewares/user";
import { Profile } from "../entities/Profile";
import { LeaveType } from "../entities/LeaveType";
import permission from "../interfaces/permission";
import { setLogDataDiff } from "../interfaces/utils";
import { Not } from "typeorm";
@Route("api/v1/org/profile/leave")
@Tags("ProfileLeave")
@Security("bearerAuth")
export class ProfileLeaveController extends Controller {
  private profileRepo = AppDataSource.getRepository(Profile);
  private leaveRepo = AppDataSource.getRepository(ProfileLeave);
  private leaveHistoryRepo = AppDataSource.getRepository(ProfileLeaveHistory);
  private leaveTypeRepository = AppDataSource.getRepository(LeaveType);

  // @Post("search")
  // public async searchProfile(
  //   @Body()
  //   body: {
  //     citizenId?: string | null;
  //     firstName?: string | null;
  //     lastName?: string | null;
  //   },
  // ) {
  //   const profileRepository = AppDataSource.getRepository(Profile);
  //   const queryBuilder = profileRepository
  //     .createQueryBuilder("profile")
  //     .leftJoinAndSelect("profile.posLevel", "posLevel")
  //     .leftJoinAndSelect("profile.posType", "posType");

  //   if (body.citizenId || body.firstName || body.lastName) {
  //     queryBuilder.where(
  //       new Brackets((qb) => {
  //         if (body.citizenId) {
  //           qb.orWhere("profile.citizenId LIKE :citizenId", { citizenId: `%${body.citizenId}%` });
  //         }
  //         if (body.firstName) {
  //           qb.orWhere("profile.firstName LIKE :firstName", { firstName: `%${body.firstName}%` });
  //         }
  //         if (body.lastName) {
  //           qb.orWhere("profile.lastName LIKE :lastName", { lastName: `%${body.lastName}%` });
  //         }
  //       }),
  //     );
  //   }

  //    const profiles = await queryBuilder.getMany();

  //    if (!profiles.length) {
  //      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบข้อมูลโปรไฟล์");
  //    }

  //    const formattedProfiles = profiles.map((profile) => ({
  //      avatar: profile.avatar,
  //      avatarName: profile.avatarName,
  //      rank: profile.rank,
  //      prefix: profile.prefix,
  //      firstName: profile.firstName,
  //      lastName: profile.lastName,
  //      citizenId: profile.citizenId,
  //      position: profile.position,
  //      posLevelId: profile.posLevelId,
  //      posLevelName: profile.posLevel.posLevelName,
  //      posTypeId: profile.posTypeId,
  //      posTypeName: profile.posType.posTypeName,
  //      email: profile.email,
  //      phone: profile.phone,
  //      keycloak: profile.keycloak,
  //      isProbation: profile.isProbation,
  //      isLeave: profile.isLeave,
  //      leaveReason: profile.leaveReason,
  //      dateRetire: profile.dateRetire,
  //      dateAppoint: profile.dateAppoint,
  //      dateRetireLaw: profile.dateRetireLaw,
  //      dateStart: profile.dateStart,
  //      govAgeAbsent: profile.govAgeAbsent,
  //      govAgePlus: profile.govAgePlus,
  //      birthDate: profile.birthDate,
  //      reasonSameDate: profile.reasonSameDate,
  //      ethnicity: profile.ethnicity,
  //      telephoneNumber: profile.telephoneNumber,
  //      nationality: profile.nationality,
  //      gender: profile.gender,
  //      relationship: profile.relationship,
  //      religion: profile.religion,
  //      bloodGroup: profile.bloodGroup,
  //    }));

  //    return new HttpSuccess(formattedProfiles);
  // }

  @Get("user")
  public async getLeaveUser(@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.leaveRepo.find({
      relations: { leaveType: true },
      where: { profileId: profile.id, isDeleted: false },
      order: { createdAt: "ASC" },
    });
    return new HttpSuccess(record);
  }

  @Get("{profileId}")
  public async getLeave(@Path() profileId: string, @Request() req: RequestWithUser) {
    let _workflow = await new permission().Workflow(req, profileId, "SYS_REGISTRY_OFFICER");
    if (_workflow == false)
      await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_OFFICER", profileId);
    const record = await this.leaveRepo.find({
      relations: { leaveType: true },
      where: { 
        profileId: profileId, 
        // status: Not("cancel") 
        isDeleted: false
      },
      order: { createdAt: "ASC" },
    });
    return new HttpSuccess(record);
  }

  @Get("admin/{profileId}")
  public async getLeaveAdmin(@Path() profileId: string, @Request() req: RequestWithUser) {
    let _workflow = await new permission().Workflow(req, profileId, "SYS_SALARY_OFFICER");
    if (_workflow == false) await new permission().PermissionGet(req, "SYS_SALARY_OFFICER");
    const record = await this.leaveRepo.find({
      relations: { leaveType: true },
      where: { profileId, isDeleted: false },
      order: { createdAt: "ASC" },
    });
    return new HttpSuccess(record);
  }

  @Get("admin/history/{leaveId}")
  public async leaveAdminHistory(@Path() leaveId: string, @Request() req: RequestWithUser) {
    const _record = await this.leaveRepo.findOneBy({ id: leaveId });
    if (_record) {
      let _workflow = await new permission().Workflow(req, leaveId, "SYS_REGISTRY_OFFICER");
      if (_workflow == false)
        await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_OFFICER", _record.profileId);
    }
    const record = await this.leaveHistoryRepo.find({
      relations: { leaveType: true },
      where: { profileLeaveId: leaveId },
      order: { createdAt: "DESC" },
    });
    return new HttpSuccess(record);
  }

  @Get("history/{leaveId}")
  public async leaveHistory(@Path() leaveId: string) {
    const record = await this.leaveHistoryRepo.find({
      relations: { leaveType: true },
      where: { profileLeaveId: leaveId },
      order: { createdAt: "DESC" },
    });
    return new HttpSuccess(record);
  }

  @Post()
  public async newLeave(@Request() req: RequestWithUser, @Body() body: CreateProfileLeave) {
    if (!body.profileId) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileId");
    }

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

    const leaveType = await this.leaveTypeRepository.findOne({
      where: { id: body.leaveTypeId },
    });
    if (!leaveType) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลประเภทลานี้");
    }
    const before = null;
    const data = new ProfileLeave();

    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 });
    const history = new ProfileLeaveHistory();
    Object.assign(history, { ...data, id: undefined });

    await this.leaveRepo.save(data, { data: req });
    setLogDataDiff(req, { before, after: data });
    history.profileLeaveId = data.id;
    await this.leaveHistoryRepo.save(history, { data: req });

    return new HttpSuccess(data.id);
  }

  @Patch("{leaveId}")
  public async editLeave(
    @Request() req: RequestWithUser,
    @Body() body: UpdateProfileLeave,
    @Path() leaveId: string,
  ) {
    const record = await this.leaveRepo.findOneBy({ id: leaveId });
    if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    await new permission().PermissionOrgUserUpdate(req, "SYS_REGISTRY_OFFICER", record.profileId);

    const leaveType = await this.leaveTypeRepository.findOne({
      where: { id: body.leaveTypeId },
    });
    if (!leaveType) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลประเภทลานี้");
    }
    const before = structuredClone(record);
    const history = new ProfileLeaveHistory();

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

    history.profileLeaveId = leaveId;
    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.leaveRepo.save(record, { data: req }),
      setLogDataDiff(req, { before, after: record }),
      this.leaveHistoryRepo.save(history, { data: req }),
    ]);

    return new HttpSuccess();
  }

  /**
   * API ลบข้อมูลการลา
   * @summary API ลบข้อมูลการลา
   * @param leaveId คีย์การลา
   */
  @Patch("update-delete/{leaveId}")
  public async updateIsDeleted(
    @Request() req: RequestWithUser,
    @Path() leaveId: string,
  ) {
    const record = await this.leaveRepo.findOneBy({ id: leaveId });
    if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    if (record.isDeleted === true) {
      return new HttpSuccess();
    }
    await new permission().PermissionOrgUserDelete(req, "SYS_REGISTRY_OFFICER", record.profileId);
    const before = structuredClone(record);
    const history = new ProfileLeaveHistory();
    const now = new Date();
    record.isDeleted = true;
    record.lastUpdateUserId = req.user.sub;
    record.lastUpdateFullName = req.user.name;
    record.lastUpdatedAt = now;

    Object.assign(history, { ...record, id: undefined });
    history.profileLeaveId = leaveId;
    history.createdUserId = req.user.sub;
    history.createdFullName = req.user.name;
    history.createdAt = now;

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

    return new HttpSuccess();
  }

  @Patch("cancel/{leaveId}")
  public async updateCancel(
    @Request() req: RequestWithUser,
    @Path() leaveId: string,
  ) {
    const record = await this.leaveRepo.findOneBy({ leaveId: leaveId });
    if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลการลา");

    const before = structuredClone(record);

    record.status = "cancel";
    record.lastUpdateUserId = req.user.sub;
    record.lastUpdateFullName = req.user.name;
    record.lastUpdatedAt = new Date();

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

    return new HttpSuccess();
  }

  @Delete("{leaveId}")
  public async deleteLeave(@Path() leaveId: string, @Request() req: RequestWithUser) {
    const _record = await this.leaveRepo.findOneBy({ id: leaveId });
    if (_record) {
      await new permission().PermissionOrgUserDelete(
        req,
        "SYS_REGISTRY_OFFICER",
        _record.profileId,
      );
    }
    await this.leaveHistoryRepo.delete({
      profileLeaveId: leaveId,
    });

    const result = await this.leaveRepo.delete({ id: leaveId });

    if (result.affected == undefined || result.affected <= 0) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    }

    return new HttpSuccess();
  }

  @Post("dump-db")
  public async newLeaveDumpDB(@Request() req: RequestWithUser, @Body() body: CreateProfileLeave) {
    if (!body.profileId) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileId");
    }

    const profile = await this.profileRepo.findOneBy({ id: body.profileId });

    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }
    const leaveType = await this.leaveTypeRepository.findOne({
      where: { name: body.leaveTypeId },
    });
    if (!leaveType) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลประเภทลานี้");
    }

    const data = new ProfileLeave();

    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 });
    data.leaveTypeId = leaveType.id;
    await this.leaveRepo.save(data);

    return new HttpSuccess();
  }
}
