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 {
  ProfileFamilyMother,
  CreateProfileEmployeeFamilyMother,
  UpdateProfileFamilyMother,
} from "../entities/ProfileFamilyMother";
import { ProfileFamilyMotherHistory } from "../entities/ProfileFamilyMotherHistory";
import Extension from "../interfaces/extension";
import permission from "../interfaces/permission";
import { setLogDataDiff } from "../interfaces/utils";
@Route("api/v1/org/profile-temp/family/mother")
@Tags("ProfileEmployeeFamilyMother")
@Security("bearerAuth")
export class ProfileFamilyMotherEmployeeTempController extends Controller {
  private profileRepo = AppDataSource.getRepository(ProfileEmployee);
  private ProfileFamilyMother = AppDataSource.getRepository(ProfileFamilyMother);
  private ProfileFamilyMotherHistory = AppDataSource.getRepository(ProfileFamilyMotherHistory);

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

    return new HttpSuccess(familyMother);
  }

  @Get("{profileEmployeeId}")
  public async getFamilyMother(@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 familyMother = await this.ProfileFamilyMother.findOne({
      where: { profileEmployeeId },
      order: { lastUpdatedAt: "DESC" },
    });

    return new HttpSuccess(familyMother);
  }

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

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

    const mapData = familyMother
      .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,
        motherPrefix: y.motherPrefix,
        motherFirstName: y.motherFirstName,
        motherLastName: y.motherLastName,
        motherLastNameOld: y.motherLastNameOld,
        motherCareer: y.motherCareer,
        motherCitizenId: y.motherCitizenId,
        motherLive: y.motherLive,
        profileFamilyMotherId: y.profileFamilyMotherId,
        profileEmployeeId: profile.id,
      }));

    return new HttpSuccess(mapData);
  }

  @Get("history/{profileEmployeeId}")
  public async familyMotherHistory(
    @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 familyMother = await this.ProfileFamilyMother.find({
      relations: ["histories"],
      order: { lastUpdatedAt: "DESC" },
      where: { profileEmployeeId: profileEmployeeId },
    });

    const mapData = familyMother
      .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,
        motherPrefix: y.motherPrefix,
        motherFirstName: y.motherFirstName,
        motherLastName: y.motherLastName,
        motherLastNameOld: y.motherLastNameOld,
        motherCareer: y.motherCareer,
        motherCitizenId: y.motherCitizenId,
        motherLive: y.motherLive,
        profileFamilyMotherId: y.profileFamilyMotherId,
        profileEmployeeId: profileEmployeeId,
      }));

    return new HttpSuccess(mapData);
  }

  @Post()
  public async FamilyMother(
    @Request() req: RequestWithUser,
    @Body() body: CreateProfileEmployeeFamilyMother,
  ) {
    await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP");
    const familyMother = Object.assign(new ProfileFamilyMother(), body);
    if (!familyMother) {
      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;
    familyMother.motherCitizenId = Extension.CheckCitizen(String(body.motherCitizenId));
    familyMother.createdUserId = req.user.sub;
    familyMother.createdFullName = req.user.name;
    familyMother.lastUpdateUserId = req.user.sub;
    familyMother.lastUpdateFullName = req.user.name;
    familyMother.createdAt = new Date();
    familyMother.lastUpdatedAt = new Date();

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

    await this.ProfileFamilyMother.save(familyMother, { data: req });
    setLogDataDiff(req, { before, after: familyMother });
    history.profileFamilyMotherId = familyMother.id;
    await this.ProfileFamilyMotherHistory.save(history, { data: req });
    //setLogDataDiff(req, { before, after: history });
    return new HttpSuccess(familyMother.id);
  }

  @Patch("{profileEmployeeId}")
  public async editFamilyMother(
    @Request() req: RequestWithUser,
    @Body() body: UpdateProfileFamilyMother,
    @Path() profileEmployeeId: string,
  ) {
    await new permission().PermissionUpdate(req, "SYS_REGISTRY_TEMP");
    const familyMother = await this.ProfileFamilyMother.findOneBy({
      profileEmployeeId: profileEmployeeId,
    });
    if (!familyMother) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    const before = structuredClone(familyMother);
    // const before_null = null;
    const history = new ProfileFamilyMotherHistory();
    Object.assign(familyMother, body);
    Object.assign(history, { ...familyMother, id: undefined });

    familyMother.motherCitizenId = Extension.CheckCitizen(String(body.motherCitizenId));
    history.profileFamilyMotherId = familyMother.id;
    familyMother.lastUpdateUserId = req.user.sub;
    familyMother.lastUpdateFullName = req.user.name;
    familyMother.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.ProfileFamilyMother.save(familyMother, { data: req }),
      setLogDataDiff(req, { before, after: familyMother }),
      this.ProfileFamilyMotherHistory.save(history, { data: req }),
      // setLogDataDiff(req, { before: before_null, after: history }),
    ]);

    return new HttpSuccess();
  }
}
