import { CreateProfileSalary, ProfileSalary } from "../entities/ProfileSalary";
import { ProfileSalaryHistory } from "../entities/ProfileSalaryHistory";
import { RequestWithUser } from "../middlewares/user";
import { AppDataSource } from "../database/data-source";
import { Profile } from "../entities/Profile";

class FunctionMain {
  private profileRepo = AppDataSource.getRepository(Profile);
  private salaryRepo = AppDataSource.getRepository(ProfileSalary);
  private salaryHistoryRepo = AppDataSource.getRepository(ProfileSalaryHistory);

  public async newSalaryFunction(req: RequestWithUser, body: CreateProfileSalary) {
    if (!body.profileId) {
      //   throw new HttpError(HttpStatus.BAD_REQUEST, "กรุณากรอก profileId");
      return;
    }

    const profile = await this.profileRepo.findOneBy({ id: body.profileId });
    if (!profile) {
      //   throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบ profile ดังกล่าว");
      return;
    }

    const dest_item = await this.salaryRepo.findOne({
      where: { profileId: body.profileId },
      order: { order: "DESC" },
    });

    const data = new ProfileSalary();

    const meta = {
      order: dest_item == null ? 1 : dest_item.order + 1,
      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 ProfileSalaryHistory();
    Object.assign(history, { ...data, id: undefined });

    await this.salaryRepo.save(data);
    history.profileSalaryId = data.id;
    await this.salaryHistoryRepo.save(history);

    return;
  }
}

export default FunctionMain;
