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 { Profile } from "../entities/Profile";
import {
  ProfileFamilyFather,
  CreateProfileFamilyFather,
  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/family/father")
@Tags("ProfileFamilyFather")
@Security("bearerAuth")
export class ProfileFamilyFatherController extends Controller {
  private profileRepo = AppDataSource.getRepository(Profile);
  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: { profileId: profile.id },
      order: { lastUpdatedAt: "DESC" },
    });

    return new HttpSuccess(familyFather);
  }

  @Get("{profileId}")
  public async getFamilyFather(@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 profile = await this.profileRepo.findOne({
      where: { id: profileId },
    });

    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }
    const familyFather = await this.ProfileFamilyFather.findOne({
      where: { profileId },
      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: { profileId: 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,
        profileId: profile.id,
      }));

    return new HttpSuccess(mapData);
  }

  @Get("history/{profileId}")
  public async familyFatherHistory(@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 profile = await this.profileRepo.findOne({
      where: { id: profileId },
    });
    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }

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

    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,
        profileId: profileId,
      }));

    return new HttpSuccess(mapData);
  }

  @Post()
  public async FamilyFather(
    @Request() req: RequestWithUser,
    @Body() body: CreateProfileFamilyFather,
  ) {
    const familyFather = Object.assign(new ProfileFamilyFather(), body);
    if (!familyFather) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    }
    const profile = await this.profileRepo.findOneBy({ id: body.profileId });
    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }
    const before = null;
    await new permission().PermissionOrgUserUpdate(req, "SYS_REGISTRY_OFFICER", profile.id);
    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("{profileId}")
  public async editFamilyFather(
    @Request() req: RequestWithUser,
    @Body() body: UpdateProfileFamilyFather,
    @Path() profileId: string,
  ) {
    await new permission().PermissionOrgUserUpdate(req, "SYS_REGISTRY_OFFICER", profileId);
    const familyFather = await this.ProfileFamilyFather.findOneBy({ profileId: profileId });
    if (!familyFather) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    const before = structuredClone(familyFather);
    // const before_null = null;
    const history = new ProfileFamilyFatherHistory();
    Object.assign(familyFather, body);
    Object.assign(history, { ...familyFather, id: undefined });

    familyFather.fatherCitizenId = Extension.CheckCitizen(String(body.fatherCitizenId));
    history.profileFamilyFatherId = familyFather.id; //profileFamilyFatherId
    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();
  }

  // @Delete("{profileId}")
  // public async deleteFamilyFather(@Path() profileId: string) {

  //   const result = await this.ProfileFamilyFather.delete({ profileId: profileId });
  //   if (result.affected == undefined || result.affected <= 0) {
  //     throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
  //   }

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