import {
  Body,
  Controller,
  Delete,
  Get,
  Patch,
  Path,
  Post,
  Request,
  Route,
  Security,
  Tags,
} from "tsoa";
import { AppDataSource } from "../database/data-source";
import { RequestWithUser } from "../middlewares/user";
import HttpError from "../interfaces/http-error";
import HttpStatus from "../interfaces/http-status";
import HttpSuccess from "../interfaces/http-success";
import { AuthRoleAttr, CreateAuthRoleAttr, UpdateAuthRoleAttr } from "../entities/AuthRoleAttr";
import { AuthRole } from "../entities/AuthRole";
import { AuthSys } from "../entities/AuthSys";

@Route("api/v1/org/auth/authRoleAttr")
@Tags("AuthRoleAttr")
@Security("bearerAuth")
export class AuthRoleAttrController extends Controller {
  private authRoleRepo = AppDataSource.getRepository(AuthRole);
  private authSysRepo = AppDataSource.getRepository(AuthSys);
  private authRoleAttrRepo = AppDataSource.getRepository(AuthRoleAttr);

  @Get("list")
  public async listAuthRoleAttr() {
    const getList = await this.authRoleAttrRepo.find();
    // if (!getList || getList.length === 0) {
    //   throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    // }
    return new HttpSuccess(getList);
  }

  @Get("{roleAttrId}")
  public async detailAuthRoleAttr(@Path() roleAttrId: string) {
    const getDetail = await this.authRoleAttrRepo.findBy({ id: roleAttrId });
    if (!getDetail) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    }
    return new HttpSuccess(getDetail);
  }

  @Post()
  public async newAuthRoleAttr(@Request() req: RequestWithUser, @Body() body: CreateAuthRoleAttr) {
    const chkAuthRole = await this.authRoleRepo.findOneBy({ id: body.authRoleId });
    if (!chkAuthRole) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล roleId");
    }

    const chkAuthSys = await this.authSysRepo.findOneBy({ id: body.authSysId });
    if (!chkAuthSys) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล systemId");
    }

    body.attrOwnership = body.attrOwnership?.toUpperCase();
    body.attrPrivilege = body.attrPrivilege?.toUpperCase();
    body.authSysId = body.authSysId?.toUpperCase();

    const data = new AuthRoleAttr();
    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 });

    await this.authRoleAttrRepo.save(data);

    return new HttpSuccess(data.id);
  }

  @Patch("{roleAttrId}")
  public async editAuthRoleAttr(
    @Body() body: UpdateAuthRoleAttr,
    @Request() req: RequestWithUser,
    @Path() roleAttrId: string,
  ) {
    const record = await this.authRoleAttrRepo.findOneBy({ id: roleAttrId });
    if (!record) throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");

    const chkAuthRole = await this.authRoleRepo.findOneBy({ id: body.authRoleId });
    if (!chkAuthRole) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล roleId");
    }

    const chkAuthSys = await this.authSysRepo.findOneBy({ id: body.authSysId });
    if (!chkAuthSys) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล systemId");
    }

    body.attrOwnership = body.attrOwnership?.toUpperCase();
    body.attrPrivilege = body.attrPrivilege?.toUpperCase();
    body.authSysId = body.authSysId?.toUpperCase();

    Object.assign(record, body);
    record.lastUpdateUserId = req.user.sub;
    record.lastUpdateFullName = req.user.name;
    record.lastUpdatedAt = new Date();

    await Promise.all([this.authRoleAttrRepo.save(record)]);

    return new HttpSuccess();
  }

  @Delete("{roleAttrId}")
  public async deleteRole(@Path() roleAttrId: string) {
    const result = await this.authRoleAttrRepo.delete({ id: roleAttrId });
    if (result.affected == undefined || result.affected <= 0)
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");

    return new HttpSuccess();
  }
}
