import { Body, Controller, 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 { RequestWithUser } from "../middlewares/user";
import { ProfileEmployee } from "../entities/ProfileEmployee";
import {
  ProfileFamilyFather,
  CreateProfileEmployeeFamilyFather,
  UpdateProfileFamilyFather,
} from "../entities/ProfileFamilyFather";
import { ProfileFamilyFatherHistory } from "../entities/ProfileFamilyFatherHistory";
import Extension from "../interfaces/extension";
import permission from "../interfaces/permission";
import { setLogDataDiff } from "../interfaces/utils";
@Route("api/v1/org/profile-temp/family/father")
@Tags("ProfileEmployeeFamilyFather")
@Security("bearerAuth")
export class ProfileFamilyFatherEmployeeTempController extends Controller {
  private profileRepo = AppDataSource.getRepository(ProfileEmployee);
  private ProfileFamilyFather = AppDataSource.getRepository(ProfileFamilyFather);
  private ProfileFamilyFatherHistory = AppDataSource.getRepository(ProfileFamilyFatherHistory);

  @Get("user")
  public async getFamilyFatherUser(@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 familyFather = await this.ProfileFamilyFather.findOne({
      where: { profileEmployeeId: profile.id },
      order: { lastUpdatedAt: "DESC" },
    });

    return new HttpSuccess(familyFather);
  }

  @Get("{profileEmployeeId}")
  public async getFamilyFather(@Path() profileEmployeeId: string, @Request() req: RequestWithUser) {
    let _workflow = await new permission().Workflow(req, profileEmployeeId, "SYS_REGISTRY_TEMP");
    if (_workflow == false) await new permission().PermissionGet(req, "SYS_REGISTRY_TEMP");
    const profile = await this.profileRepo.findOne({
      where: { id: profileEmployeeId },
    });

    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }
    const familyFather = await this.ProfileFamilyFather.findOne({
      where: { profileEmployeeId },
      order: { lastUpdatedAt: "DESC" },
    });

    return new HttpSuccess(familyFather);
  }

  /**
   *
   * @summary ประวัติแก้ไขครอบครัว by keycloak
   *
   */
  @Get("history/user")
  public async familyFatherHistoryUser(@Request() request: RequestWithUser) {
    const profile = await this.profileRepo.findOneBy({ keycloak: request.user.sub });
    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }

    const familyFather = await this.ProfileFamilyFather.find({
      relations: ["histories"],
      order: { lastUpdatedAt: "DESC" },
      where: { profileEmployeeId: profile.id },
    });

    const mapData = familyFather
      .flatMap((x) => x.histories)
      .map((y) => ({
        id: y.id,
        createdAt: y.createdAt,
        createdUserId: y.createdUserId,
        lastUpdatedAt: y.lastUpdatedAt,
        lastUpdateUserId: y.lastUpdateUserId,
        createdFullName: y.createdFullName,
        lastUpdateFullName: y.lastUpdateFullName,
        fatherPrefix: y.fatherPrefix,
        fatherFirstName: y.fatherFirstName,
        fatherLastName: y.fatherLastName,
        fatherCareer: y.fatherCareer,
        fatherCitizenId: y.fatherCitizenId,
        fatherLive: y.fatherLive,
        profileFamilyFatherId: y.profileFamilyFatherId,
        profileEmployeeId: profile.id,
      }));

    return new HttpSuccess(mapData);
  }

  @Get("history/{profileEmployeeId}")
  public async familyFatherHistory(
    @Path() profileEmployeeId: string,
    @Request() req: RequestWithUser,
  ) {
    let _workflow = await new permission().Workflow(req, profileEmployeeId, "SYS_REGISTRY_TEMP");
    if (_workflow == false) await new permission().PermissionGet(req, "SYS_REGISTRY_TEMP");
    const profile = await this.profileRepo.findOne({
      where: { id: profileEmployeeId },
    });
    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }

    const familyFather = await this.ProfileFamilyFather.find({
      relations: ["histories"],
      order: { lastUpdatedAt: "DESC" },
      where: { profileEmployeeId: profileEmployeeId },
    });

    const mapData = familyFather
      .flatMap((x) => x.histories)
      .map((y) => ({
        id: y.id,
        createdAt: y.createdAt,
        createdUserId: y.createdUserId,
        lastUpdatedAt: y.lastUpdatedAt,
        lastUpdateUserId: y.lastUpdateUserId,
        createdFullName: y.createdFullName,
        lastUpdateFullName: y.lastUpdateFullName,
        fatherPrefix: y.fatherPrefix,
        fatherFirstName: y.fatherFirstName,
        fatherLastName: y.fatherLastName,
        fatherCareer: y.fatherCareer,
        fatherCitizenId: y.fatherCitizenId,
        fatherLive: y.fatherLive,
        profileFamilyFatherId: y.profileFamilyFatherId,
        profileEmployeeId: profileEmployeeId,
      }));

    return new HttpSuccess(mapData);
  }

  @Post()
  public async FamilyFather(
    @Request() req: RequestWithUser,
    @Body() body: CreateProfileEmployeeFamilyFather,
  ) {
    await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP");
    const familyFather = Object.assign(new ProfileFamilyFather(), body);
    if (!familyFather) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    }
    const profile = await this.profileRepo.findOneBy({ id: body.profileEmployeeId });
    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }
    const before = null;
    familyFather.fatherCitizenId = Extension.CheckCitizen(String(body.fatherCitizenId));
    familyFather.createdUserId = req.user.sub;
    familyFather.createdFullName = req.user.name;
    familyFather.lastUpdateUserId = req.user.sub;
    familyFather.lastUpdateFullName = req.user.name;
    familyFather.createdAt = new Date();
    familyFather.lastUpdatedAt = new Date();

    const history = new ProfileFamilyFatherHistory();
    Object.assign(history, { ...familyFather, id: undefined });

    await this.ProfileFamilyFather.save(familyFather, { data: req });
    setLogDataDiff(req, { before, after: familyFather });
    history.profileFamilyFatherId = familyFather.id;
    await this.ProfileFamilyFatherHistory.save(history, { data: req });
    //setLogDataDiff(req, { before, after: history });

    return new HttpSuccess(familyFather.id);
  }

  @Patch("{profileEmployeeId}")
  public async editFamilyFather(
    @Request() req: RequestWithUser,
    @Body() body: UpdateProfileFamilyFather,
    @Path() profileEmployeeId: string,
  ) {
    await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP");
    const familyFather = await this.ProfileFamilyFather.findOneBy({
      profileEmployeeId: profileEmployeeId,
    });
    if (!familyFather) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");

    const history = new ProfileFamilyFatherHistory();
    Object.assign(familyFather, body);
    Object.assign(history, { ...familyFather, id: undefined });
    const before = structuredClone(familyFather);
    // const before_null = null;
    familyFather.fatherCitizenId = Extension.CheckCitizen(String(body.fatherCitizenId));
    history.profileFamilyFatherId = familyFather.id;
    familyFather.lastUpdateUserId = req.user.sub;
    familyFather.lastUpdateFullName = req.user.name;
    familyFather.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.ProfileFamilyFather.save(familyFather, { data: req }),
      setLogDataDiff(req, { before, after: familyFather }),
      this.ProfileFamilyFatherHistory.save(history, { data: req }),
      // setLogDataDiff(req, { before: before_null, after: history }),
    ]);

    return new HttpSuccess();
  }
}
