import {
  Body,
  Controller,
  Example,
  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 {
  ProfileFamilyCouple,
  CreateProfileFamilyCouple,
  UpdateProfileFamilyCouple,
} from "../entities/ProfileFamilyCouple";
import { ProfileFamilyCoupleHistory } from "../entities/ProfileFamilyCoupleHistory";
import Extension from "../interfaces/extension";
import permission from "../interfaces/permission";
import { setLogDataDiff } from "../interfaces/utils";
@Route("api/v1/org/profile/family/couple")
@Tags("ProfileFamilyCouple")
@Security("bearerAuth")
export class ProfileFamilyCoupleController extends Controller {
  private profileRepo = AppDataSource.getRepository(Profile);
  private ProfileFamilyCouple = AppDataSource.getRepository(ProfileFamilyCouple);
  private ProfileFamilyCoupleHistory = AppDataSource.getRepository(ProfileFamilyCoupleHistory);

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

    return new HttpSuccess(familyCouple);
  }

  @Get("{profileId}")
  public async getFamilyCouple(@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 familyCouple = await this.ProfileFamilyCouple.findOne({
      where: { profileId },
      order: { lastUpdatedAt: "DESC" },
    });

    return new HttpSuccess(familyCouple);
  }

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

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

    const mapData = familyCouple
      .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,
        couplePrefix: y.couplePrefix,
        coupleFirstName: y.coupleFirstName,
        coupleLastName: y.coupleLastName,
        coupleLastNameOld: y.coupleLastNameOld,
        coupleCareer: y.coupleCareer,
        coupleCitizenId: y.coupleCitizenId,
        coupleLive: y.coupleLive,
        relationship: y.relationship,
        profileFamilyCoupleId: y.profileFamilyCoupleId,
        profileId: profile.id,
      }));

    return new HttpSuccess(mapData);
  }

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

    const mapData = familyCouple
      .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,
        couplePrefix: y.couplePrefix,
        coupleFirstName: y.coupleFirstName,
        coupleLastName: y.coupleLastName,
        coupleLastNameOld: y.coupleLastNameOld,
        coupleCareer: y.coupleCareer,
        coupleCitizenId: y.coupleCitizenId,
        coupleLive: y.coupleLive,
        relationship: y.relationship,
        profileFamilyCoupleId: y.profileFamilyCoupleId,
        profileId: profileId,
      }));

    return new HttpSuccess(mapData);
  }

  @Post()
  public async FamilyCouple(
    @Request() req: RequestWithUser,
    @Body() body: CreateProfileFamilyCouple,
  ) {
    const familyCouple = Object.assign(new ProfileFamilyCouple(), body);
    if (!familyCouple) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    }
    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);
    await this.ProfileFamilyCouple.update(
      { profileId: profile.id },
      { couple: false },
    );
    const before = null;
    familyCouple.coupleCitizenId = Extension.CheckCitizen(String(body.coupleCitizenId));
    familyCouple.createdUserId = req.user.sub;
    familyCouple.createdFullName = req.user.name;
    familyCouple.lastUpdateUserId = req.user.sub;
    familyCouple.lastUpdateFullName = req.user.name;
    familyCouple.createdAt = new Date();
    familyCouple.lastUpdatedAt = new Date();
    familyCouple.couple = true;
    profile.relationship = familyCouple.relationship; //update profileEmployee.relationship
    const history = new ProfileFamilyCoupleHistory();
    Object.assign(history, { ...familyCouple, id: undefined });

    await this.profileRepo.save(profile, { data: req });
    setLogDataDiff(req, { before, after: profile });
    await this.ProfileFamilyCouple.save(familyCouple, { data: req });
    setLogDataDiff(req, { before, after: familyCouple });
    history.profileFamilyCoupleId = familyCouple.id;
    await this.ProfileFamilyCoupleHistory.save(history, { data: req });
    //setLogDataDiff(req, { before, after: history });
    return new HttpSuccess(familyCouple.id);
  }

  @Patch("{profileId}")
  public async editFamilyCouple(
    @Request() req: RequestWithUser,
    @Body() body: UpdateProfileFamilyCouple,
    @Path() profileId: string,
  ) {
    await new permission().PermissionOrgUserUpdate(req, "SYS_REGISTRY_OFFICER", profileId);
    const familyCouple = await this.ProfileFamilyCouple.findOneBy({ profileId: profileId });
    if (!familyCouple) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    const before = structuredClone(familyCouple);
    // const before_null = null;
    const history = new ProfileFamilyCoupleHistory();
    Object.assign(familyCouple, body);
    Object.assign(history, { ...familyCouple, id: undefined });

    familyCouple.coupleCitizenId = Extension.CheckCitizen(String(body.coupleCitizenId));
    history.profileFamilyCoupleId = familyCouple.id;
    familyCouple.lastUpdateUserId = req.user.sub;
    familyCouple.lastUpdateFullName = req.user.name;
    familyCouple.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.ProfileFamilyCouple.save(familyCouple, { data: req }),
      setLogDataDiff(req, { before, after: familyCouple }),
      this.ProfileFamilyCoupleHistory.save(history, { data: req }),
      // setLogDataDiff(req, { before: before_null, after: history }),
    ]);

    return new HttpSuccess();
  }
}
