import {
  Body,
  Controller,
  Delete,
  Get,
  Patch,
  Path,
  Post,
  Request,
  Route,
  Security,
  Tags,
} from "tsoa";
import { AppDataSource } from "../database/data-source";
import {
  CreateProfileActpositionEmployee,
  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 { ProfileEmployee } from "../entities/ProfileEmployee";
import permission from "../interfaces/permission";
import { setLogDataDiff } from "../interfaces/utils";
@Route("api/v1/org/profile-employee/actposition")
@Tags("ProfileActpositionEmployee")
@Security("bearerAuth")
export class ProfileActpositionEmployeeController extends Controller {
  private profileEmployeeRepo = AppDataSource.getRepository(ProfileEmployee);
  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.profileEmployeeRepo.findOneBy({ keycloak: request.user.sub });
    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }
    const getProfileActpositionId = await this.profileActpositionRepo.find({
      where: { profileEmployeeId: profile.id, isDeleted: false },
      order: { createdAt: "ASC" },
    });
    if (!getProfileActpositionId) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    }
    return new HttpSuccess(getProfileActpositionId);
  }

  @Get("{profileEmployeeId}")
  public async detailProfileActposition(
    @Path() profileEmployeeId: string,
    @Request() req: RequestWithUser,
  ) {
    let _workflow = await new permission().Workflow(req, profileEmployeeId, "SYS_REGISTRY_EMP");
    if (_workflow == false)
      await new permission().PermissionOrgUserGet(req, "SYS_REGISTRY_EMP", profileEmployeeId);
    const getProfileActpositionId = await this.profileActpositionRepo.find({
      where: { profileEmployeeId: profileEmployeeId, isDeleted: false },
      order: { createdAt: "ASC" },
    });
    if (!getProfileActpositionId) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    }
    return new HttpSuccess(getProfileActpositionId);
  }

  @Get("admin/history/{actpositionId}")
  public async getProfileAdminActpositionHistory(
    @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_EMP");
      if (_workflow == false)
        await new permission().PermissionOrgUserGet(
          req,
          "SYS_REGISTRY_EMP",
          _record.profileEmployeeId,
        );
    }
    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({
      where: { profileActpositionId: actpositionId },
      order: { createdAt: "DESC" },
    });
    if (!record) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    }
    return new HttpSuccess(record);
  }

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

    const profile = await this.profileEmployeeRepo.findOneBy({ id: body.profileEmployeeId });
    if (!profile) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
    }
    await new permission().PermissionOrgUserUpdate(req, "SYS_REGISTRY_EMP", 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_EMP",
      record.profileEmployeeId,
    );
    const before = structuredClone(record);
    // const before_null = null;
    const history = new ProfileActpositionHistory();

    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();
  }

  @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_EMP",
        _record.profileEmployeeId,
      );
    }
    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();
  }
}
