import {
  Body,
  Controller,
  Delete,
  Get,
  Patch,
  Path,
  Post,
  Request,
  Route,
  Security,
  Tags,
} from "tsoa";
import { AppDataSource } from "../database/data-source";
import { Profile } from "../entities/Profile";
import {
  CreateProfileActposition,
  ProfileActposition,
  UpdateProfileActposition,
} from "../entities/ProfileActposition";
import { ProfileActpositionHistory } from "../entities/ProfileActpositionHistory";
import { RequestWithUser } from "../middlewares/user";
import HttpError from "../interfaces/http-error";
import HttpStatus from "../interfaces/http-status";
import HttpSuccess from "../interfaces/http-success";
import permission from "../interfaces/permission";
import { setLogDataDiff } from "../interfaces/utils";
@Route("api/v1/org/profile/actposition")
@Tags("ProfileActposition")
@Security("bearerAuth")
export class ProfileActpositionController extends Controller {
  private profileRepo = AppDataSource.getRepository(Profile);
  private profileActpositionRepo = AppDataSource.getRepository(ProfileActposition);
  private profileActpositionHistoryRepo = AppDataSource.getRepository(ProfileActpositionHistory);

  @Get("user")
  public async detailProfileActpositionUser(@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 getProfileActpositionId = await this.profileActpositionRepo.find({
      where: { profileId: profile.id, isDeleted: false },
      order: { createdAt: "ASC" },
    });
    if (!getProfileActpositionId) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    }
    return new HttpSuccess(getProfileActpositionId);
  }

  @Get("{profileId}")
  public async detailProfileActposition(
    @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 getProfileActpositionId = await this.profileActpositionRepo.find({
      where: { profileId: profileId, isDeleted: false },
      order: { createdAt: "ASC" },
    });
    if (!getProfileActpositionId) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    }
    return new HttpSuccess(getProfileActpositionId);
  }

  @Get("admin/history/{actpositionId}")
  public async getProfileActpositionAdminHistory(
    @Path() actpositionId: string,
    @Request() req: RequestWithUser,
  ) {
    const _record = await this.profileActpositionRepo.findOneBy({ id: actpositionId });
    if (_record) {
      let _workflow = await new permission().Workflow(req, actpositionId, "SYS_REGISTRY_OFFICER");
      if (_workflow == false)
        await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_OFFICER", _record.profileId);
    }

    const record = await this.profileActpositionHistoryRepo.find({
      where: { profileActpositionId: actpositionId },
      order: { createdAt: "DESC" },
    });

    if (!record) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    }
    return new HttpSuccess(record);
  }

  @Get("history/{actpositionId}")
  public async getProfileActpositionHistory(@Path() actpositionId: string) {
    const record = await this.profileActpositionHistoryRepo.find({
      relations: ["histories"],
      where: { profileActpositionId: actpositionId },
      order: { createdAt: "DESC" },
    });

    if (!record) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    }
    
    const mappedRecords = record.map(history => {
      const firstHistory = history.histories ?? []; 
    
      return {
        id: history.id,
        createdAt: history.createdAt,
        createdUserId: history.createdUserId,
        lastUpdatedAt: history.lastUpdatedAt,
        lastUpdateUserId: history.lastUpdateUserId,
        createdFullName: history.createdFullName,
        lastUpdateFullName: history.lastUpdateFullName,
        dateStart: history.dateStart,
        dateEnd: history.dateEnd,
        posNo: history.posNo,
        position: history.position,
        status: history.status,
        profileActpositionId: history.profileActpositionId,
        refCommandNo: firstHistory?.refCommandNo ?? null, 
      };
    });
    

    return new HttpSuccess(mappedRecords);
  }

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

    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);
    const before = null;
    const data = new ProfileActposition();
    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 ProfileActpositionHistory();
    Object.assign(history, { ...data, id: undefined });

    await this.profileActpositionRepo.save(data, { data: req });
    setLogDataDiff(req, { before, after: data });
    history.profileActpositionId = data.id;
    await this.profileActpositionHistoryRepo.save(history, { data: req });
    //setLogDataDiff(req, { before, after: history });
    return new HttpSuccess(data.id);
  }

  @Patch("{actpositionId}")
  public async editProfileActposition(
    @Body() body: UpdateProfileActposition,
    @Request() req: RequestWithUser,
    @Path() actpositionId: string,
  ) {
    const record = await this.profileActpositionRepo.findOneBy({ id: actpositionId });
    if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    await new permission().PermissionOrgUserUpdate(req, "SYS_REGISTRY_OFFICER", record.profileId);

    const history = new ProfileActpositionHistory();
    const before = structuredClone(record);
    // const before_null = null;
    Object.assign(record, body);
    Object.assign(history, { ...record, id: undefined });

    history.profileActpositionId = actpositionId;
    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.profileActpositionRepo.save(record, { data: req }),
      setLogDataDiff(req, { before, after: record }),
      this.profileActpositionHistoryRepo.save(history, { data: req }),
      // setLogDataDiff(req, { before: before_null, after: history }),
    ]);

    return new HttpSuccess();
  }

  /**
   * API ลบข้อมูลรักษาการในตำแหน่ง
   * @summary API ลบข้อมูลรักษาการในตำแหน่ง
   * @param actpositionId คีย์รักษาการในตำแหน่ง
   */
  @Patch("update-delete/{actpositionId}")
  public async updateIsDeletedTraining(
    @Request() req: RequestWithUser,
    @Path() actpositionId: string,
  ) {
    const record = await this.profileActpositionRepo.findOneBy({ id: actpositionId });
    if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    if (record.isDeleted === true) {
      return new HttpSuccess();
    }
    await new permission().PermissionOrgUserDelete(req, "SYS_REGISTRY_OFFICER", record.profileId);
    const before = structuredClone(record);
    const history = new ProfileActpositionHistory();
    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.createdUserId = req.user.sub;
    history.createdFullName = req.user.name;
    history.createdAt = now;

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

    return new HttpSuccess();
  }

  @Delete("{actpositionId}")
  public async deleteProfileActposition(
    @Path() actpositionId: string,
    @Request() req: RequestWithUser,
  ) {
    const _record = await this.profileActpositionRepo.findOneBy({ id: actpositionId });
    if (_record) {
      await new permission().PermissionOrgUserDelete(
        req,
        "SYS_REGISTRY_OFFICER",
        _record.profileId,
      );
    }
    await this.profileActpositionHistoryRepo.delete({
      profileActpositionId: actpositionId,
    });

    const result = await this.profileActpositionRepo.delete({ id: actpositionId });

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

    return new HttpSuccess();
  }
}
