import {
  Body,
  Controller,
  Delete,
  Get,
  Patch,
  Path,
  Post,
  Request,
  Route,
  Security,
  Tags,
} from "tsoa";
import { AppDataSource } from "../database/data-source";
import HttpSuccess from "../interfaces/http-success";
import HttpStatus from "../interfaces/http-status";
import HttpError from "../interfaces/http-error";
import { ProfileChangeNameHistory } from "../entities/ProfileChangeNameHistory";
import { RequestWithUser } from "../middlewares/user";
import {
  CreateProfileChangeNameEmployee,
  ProfileChangeName,
  UpdateProfileChangeName,
} from "../entities/ProfileChangeName";
import { ProfileEmployee } from "../entities/ProfileEmployee";
import permission from "../interfaces/permission";
import { updateHolderProfileHistory } from "../services/PositionService";
import { updateName } from "../keycloak";
import { setLogDataDiff } from "../interfaces/utils";
@Route("api/v1/org/profile-employee/changeName")
@Tags("ProfileChangeNameEmployee")
@Security("bearerAuth")
export class ProfileChangeNameEmployeeController extends Controller {
  private profileEmployeeRepo = AppDataSource.getRepository(ProfileEmployee);
  private changeNameRepository = AppDataSource.getRepository(ProfileChangeName);
  private changeNameHistoryRepository = AppDataSource.getRepository(ProfileChangeNameHistory);

  @Get("user")
  public async getChangeNameUser(@Request() request: { user: Record<string, any> }) {
    const profile = await this.profileEmployeeRepo.findOneBy({ keycloak: request.user.sub });
    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }
    const lists = await this.changeNameRepository.find({
      where: { profileEmployeeId: profile.id, isDeleted: false },
      order: { createdAt: "ASC" },
    });
    return new HttpSuccess(lists);
  }

  @Get("{profileEmployeeId}")
  public async getChangeName(@Path() profileEmployeeId: string, @Request() req: RequestWithUser) {
    let _workflow = await new permission().Workflow(req, profileEmployeeId, "SYS_REGISTRY_EMP");
    if (_workflow == false)
      await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_EMP", profileEmployeeId);
    const lists = await this.changeNameRepository.find({
      where: { profileEmployeeId: profileEmployeeId, isDeleted: false },
      order: { createdAt: "ASC" },
    });
    return new HttpSuccess(lists);
  }

  @Get("history/{changeNameId}")
  public async changeNameHistory(@Path() changeNameId: string, @Request() req: RequestWithUser) {
    const _record = await this.changeNameRepository.findOneBy({ id: changeNameId });
    if (_record) {
      let _workflow = await new permission().Workflow(req, changeNameId, "SYS_REGISTRY_EMP");
      if (_workflow == false)
        await new permission().PermissionOrgUserGet(
          req,
          "SYS_REGISTRY_EMP",
          _record.profileEmployeeId,
        );
    }
    const record = await this.changeNameHistoryRepository.find({
      where: { profileChangeNameId: changeNameId },
      order: { createdAt: "DESC" },
    });
    return new HttpSuccess(record);
  }

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

    const profile = await this.profileEmployeeRepo.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 ProfileChangeName();

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

    await this.changeNameRepository.save(data, { data: req });
    setLogDataDiff(req, { before, after: data });
    history.profileChangeNameId = data.id;
    await this.changeNameHistoryRepository.save(history, { data: req });
    //setLogDataDiff(req, { before, after: history });

    profile.firstName = body.firstName ?? profile.firstName;
    profile.lastName = body.lastName ?? profile.lastName;
    // profile.prefix = body.prefix ?? profile.prefix; //old
    profile.rank = body.rank ?? profile.rank;
    // profile.prefixMain = profile.rank ?? profile.prefix; // old
    profile.prefixMain = profile.prefix;
    profile.prefix = profile.rank && profile.rank.length > 0 ? profile.rank : profile.prefixMain;
    await this.profileEmployeeRepo.save(profile, { data: req });
    setLogDataDiff(req, { before, after: profile });

    if (profile != null && profile.keycloak != null && profile.isDelete === false) {
      const result = await updateName(
        profile.keycloak,
        profile.firstName,
        profile.lastName,
        profile.prefix,
      );
      if (!result) {
        throw new Error(result.errorMessage);
      }
    }

    // บันทึกประวัติคนครองตำแหน่ง (ถ้า profile นี้ครองตำแหน่งอยู่)
    await updateHolderProfileHistory(profile.id, req, "EMPLOYEE");

    return new HttpSuccess(data.id);
  }

  @Patch("{changeNameId}")
  public async editChangeName(
    @Request() req: RequestWithUser,
    @Body() body: UpdateProfileChangeName,
    @Path() changeNameId: string,
  ) {
    const record = await this.changeNameRepository.findOneBy({ id: changeNameId });
    if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    await new permission().PermissionOrgUserUpdate(
      req,
      "SYS_REGISTRY_EMP",
      record.profileEmployeeId,
    );

    const history = new ProfileChangeNameHistory();

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

    history.profileChangeNameId = changeNameId;
    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.changeNameRepository.save(record),
      this.changeNameHistoryRepository.save(history),
    ]);

    const chkLastRecord = await this.changeNameRepository.findOne({
      where: {
        profileEmployeeId: record.profileEmployeeId,
      },
      order: {
        createdAt: "DESC",
      },
    });
    if (!chkLastRecord) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");

    const profile = await this.profileEmployeeRepo.findOneBy({ id: record.profileEmployeeId });

    if (profile && chkLastRecord.id === record.id) {
      profile.firstName = body.firstName ?? profile.firstName;
      profile.lastName = body.lastName ?? profile.lastName;
      // profile.prefix = body.prefix ?? profile.prefix; //old
      profile.rank = body.rank ?? profile.rank;
      // profile.prefixMain = profile.rank ?? profile.prefix; // old
      profile.prefixMain = profile.prefix;
      profile.prefix = profile.rank && profile.rank.length > 0 ? profile.rank : profile.prefixMain;
      await this.profileEmployeeRepo.save(profile);
    }

    return new HttpSuccess();
  }

  /**
   * API ลบข้อมูลประวัติการเปลี่ยนชื่อ - นามสกุล
   * @summary API ลบข้อมูลประวัติการเปลี่ยนชื่อ - นามสกุล
   * @param trainingId คีย์ประวัติการเปลี่ยนชื่อ - นามสกุล
   */
  @Patch("update-delete/{changeNameId}")
  public async updateIsDeleted(@Request() req: RequestWithUser, @Path() changeNameId: string) {
    const record = await this.changeNameRepository.findOneBy({ id: changeNameId });
    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 ProfileChangeNameHistory();
    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.profileChangeNameId = changeNameId;
    history.createdUserId = req.user.sub;
    history.createdFullName = req.user.name;
    history.createdAt = now;

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

    return new HttpSuccess();
  }

  @Delete("{changeNameId}")
  public async deleteTraning(@Path() changeNameId: string, @Request() req: RequestWithUser) {
    const _record = await this.changeNameRepository.findOneBy({ id: changeNameId });
    if (_record) {
      await new permission().PermissionOrgUserDelete(
        req,
        "SYS_REGISTRY_EMP",
        _record.profileEmployeeId,
      );
    }
    await this.changeNameHistoryRepository.delete({
      profileChangeNameId: changeNameId,
    });

    const result = await this.changeNameRepository.delete({ id: changeNameId });

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

    return new HttpSuccess();
  }
}
