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 HttpStatusCode from "../interfaces/http-status";
import { AuthSys, CreateAuthSys, UpdateAuthSys } from "../entities/AuthSys";

@Route("api/v1/org/auth/authSys")
@Tags("AuthSystem")
@Security("bearerAuth")
export class AuthSysController extends Controller {
  private authSysRepo = AppDataSource.getRepository(AuthSys);

  @Get("list")
  public async listAuthSys() {
    const getList = await this.authSysRepo.find({
      select: ["id", "parentId", "sysName", "sysDescription", "order"],
    });

    if (!getList || getList.length === 0) {
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");
    }

    const lists = getList
      .filter((x) => x.parentId == null)
      .map((item) => {
        return {
          ...item,
          children: getList.filter((x) => x.parentId == item.id).sort((a, b) => a.order - b.order),
        };
      })
      .sort((a, b) => a.order - b.order);

    return new HttpSuccess(lists);
  }

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

  @Post()
  public async newAuthSys(@Request() req: RequestWithUser, @Body() body: CreateAuthSys) {
    if (!body.id) {
      throw new HttpError(HttpStatus.BAD_REQUEST, "ไม่พบค่าไอดีที่ส่งมา");
    }

    body.id = body.id?.toUpperCase();

    const data = new AuthSys();
    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.authSysRepo.save(data);

    return new HttpSuccess(data.id);
  }

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

    body.id = body.id?.toUpperCase();

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

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

    return new HttpSuccess();
  }

  @Delete("{systemId}")
  public async deleteAuthSys(@Path() systemId: string) {
    let result: any;
    try {
      result = await this.authSysRepo.delete({ id: systemId });
    } catch {
      throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่สามารถลบข้อมูลได้");
    }
    if (result.affected == undefined || result.affected <= 0)
      throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล");

    return new HttpSuccess();
  }
}
