import {
  ExecutionContext,
  UnauthorizedException,
  createParamDecorator,
} from '@nestjs/common';
import { eUserType } from 'src/common/auth/type';

export type AuthPayload = {
  id: string | number;
  account: string;
  type: eUserType;
  containsPassword: boolean;
};
export type RefreshTokenPayload = AuthPayload & {
  prefix: string;
  tid: string;
};
// export type AuthUserPayloadType = JwtAccessTokenPayload;

export const AuthAllPayload = createParamDecorator(
  async (_: unknown, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    const user = request.user;
    return user;
  },
);

export const AuthUser = createParamDecorator(
  async (_: unknown, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    const user = request.user;
    if (user.type !== eUserType.USER) throw new UnauthorizedException();
    return user;
  },
);

export const AuthTenant = createParamDecorator(
  async (_: unknown, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    const user = <AuthPayload>request.user;
    if (user.type !== eUserType.TENANT) throw new UnauthorizedException();
    return user;
  },
);

export const AuthAdmin = createParamDecorator(
  async (_: unknown, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    const user = <AuthPayload>request.user;
    if (user.type !== eUserType.ADMIN) throw new UnauthorizedException();
    return user;
  },
);
