import {
  createParamDecorator,
  ExecutionContext,
  UnauthorizedException,
} from '@nestjs/common';
import { JwtAccessTokenPayload } from './type';

export type AuthUserPayloadType = JwtAccessTokenPayload;

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

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

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