import { Controller, Route, Tags, SuccessResponse, Response, Post, Body } from "tsoa";
import HttpSuccess from "../interfaces/http-success";
import HttpStatus from "../interfaces/http-status";
import CallAPI from "../interfaces/call-api";
import HttpError from "../interfaces/http-error";

@Route("api/v1/org/login")
@Tags("Profile")
@Response(
  HttpStatus.INTERNAL_SERVER_ERROR,
  "เกิดข้อผิดพลาด ไม่สามารถแสดงรายการได้ กรุณาลองใหม่ในภายหลัง",
)
@SuccessResponse(HttpStatus.OK, "สำเร็จ")
export class LoginController extends Controller {
  /**
   * API login
   *
   * @summary - login
   *
   */
  @Post()
  async login(
    @Body()
    body: {
      username: string;
      password: string;
    },
  ) {
    const data = {
      client_id: "gettoken",
      client_secret: process.env.AUTH_ACCOUNT_SECRET,
      grant_type: "password",
      requested_token_type: "urn:ietf:params:oauth:token-type:refresh_token",
      username: body.username,
      password: body.password,
    };
    let _data: any = null;
    await Promise.all([
      await new CallAPI()
        .PostDataKeycloak(`/realms/${process.env.KC_REALMS}/protocol/openid-connect/token`, data)
        .then(async (x) => {
          _data = x;
        })
        .catch(async (x) => {
          throw new HttpError(HttpStatus.UNAUTHORIZED, "ชื่อผู้ใช้งานหรือรหัสผ่านไม่ถูกต้อง");
        }),
    ]);
    if (_data == null) {
      return new HttpError(HttpStatus.UNAUTHORIZED, "ชื่อผู้ใช้งานหรือรหัสผ่านไม่ถูกต้อง");
    } else {
      return new HttpSuccess(_data);
    }
  }

  /**
   * API login checkin
   *
   * @summary - login checkin
   *
   */
  @Post("checkin")
  async loginCheckin(
    @Body()
    body: {
      username: string;
      password: string;
    },
  ) {
    const data = {
      client_id: "gettoken-checkin",
      client_secret: process.env.KC_CHECKIN_SECRET,
      grant_type: "password",
      // requested_token_type: "urn:ietf:params:oauth:token-type:refresh_token",
      username: body.username,
      password: body.password,
      // scope: "offline_access",
    };
    let _data: any = null;
    await Promise.all([
      await new CallAPI()
        .PostDataKeycloak(`/realms/${process.env.KC_REALMS}/protocol/openid-connect/token`, data)
        .then(async (x) => {
          _data = x;
        })
        .catch(async (x) => {
          throw new HttpError(HttpStatus.UNAUTHORIZED, "ชื่อผู้ใช้งานหรือรหัสผ่านไม่ถูกต้อง");
        }),
    ]);
    if (_data == null) {
      return new HttpError(HttpStatus.UNAUTHORIZED, "ชื่อผู้ใช้งานหรือรหัสผ่านไม่ถูกต้อง");
    } else {
      return new HttpSuccess(_data);
    }
  }
}
