import { ConflictException, ForbiddenException, Injectable } from "@nestjs/common";
import * as argon from '@node-rs/argon2';
import { Prisma } from "generated/prisma/client";
import { PrismaService } from "src/prisma/prisma.service";
import { AuthDto } from "./dto";
import { JwtService } from "@nestjs/jwt";

@Injectable()
export class AuthService {
    constructor(
        private prisma: PrismaService,
        private jwt: JwtService
    ) { }


    async login(dto: AuthDto) {
        const user = await this.prisma.user.findUnique({
            where: {
                email: dto.email
            }
        });
        if (!user) {
            throw new ForbiddenException("Email not found");
        }
        const pwMatched = await argon.verify(user.hash, dto.password);
        if (!pwMatched) {
            throw new ForbiddenException("Password doesn't match");
        }
        // remove hash before returning (security best practice)
        delete (user as any).hash;

        return await this.signToken(user.id, user.email);
    }

    async signToken(userId: string, email: string): Promise<object> {
        const payload = {
            sub: userId,
            email
        }
        const token = await this.jwt.signAsync(payload)
        // console.log(token)
        return { access_token: token }
    }
}