"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthService = void 0;
const common_1 = require("@nestjs/common");
const config_1 = require("@nestjs/config");
const jwt_1 = require("@nestjs/jwt");
const bcrypt = require("bcryptjs");
const prisma_service_1 = require("../prisma/prisma.service");
const roles_1 = require("../../common/roles");
let AuthService = class AuthService {
    constructor(prisma, jwt, config) {
        this.prisma = prisma;
        this.jwt = jwt;
        this.accessSecret = config.get('JWT_ACCESS_SECRET', '');
        this.refreshSecret = config.get('JWT_REFRESH_SECRET', '');
        this.accessExpiresIn = config.get('JWT_ACCESS_EXPIRES_IN', '15m');
        this.refreshExpiresIn = config.get('JWT_REFRESH_EXPIRES_IN', '30d');
    }
    async registerOnline(dto) {
        const existing = await this.prisma.user.findFirst({ where: { OR: [{ email: dto.email }, { phone: dto.phone }] } });
        if (existing)
            throw new common_1.BadRequestException('Email or phone already exists');
        const passwordHash = await bcrypt.hash(dto.password, 10);
        const user = await this.prisma.user.create({ data: { fullName: dto.fullName, email: dto.email, phone: dto.phone, passwordHash, role: roles_1.UserRole.STUDENT_ONLINE }, select: { id: true, role: true } });
        return { userId: user.id, role: 'student_online', requiresOtp: false };
    }
    async registerOffline(dto) {
        const existingMatric = await this.prisma.user.findUnique({ where: { matricNumber: dto.matricNumber } });
        if (existingMatric)
            throw new common_1.BadRequestException('Matric number already exists');
        const user = await this.prisma.user.create({
            data: { fullName: dto.fullName, email: dto.email, phone: dto.phone, matricNumber: dto.matricNumber, department: dto.department, level: dto.level, role: roles_1.UserRole.STUDENT_OFFLINE, profileVisible: false },
            select: { id: true, role: true },
        });
        return { userId: user.id, role: 'student_offline', privacy: { matricNumberVisibleTo: ['self', 'admin'] } };
    }
    async login(dto) {
        const user = await this.prisma.user.findFirst({ where: { OR: [{ email: dto.emailOrPhone }, { phone: dto.emailOrPhone }] } });
        if (!user || !user.passwordHash)
            throw new common_1.UnauthorizedException('Invalid credentials');
        const okPass = await bcrypt.compare(dto.password, user.passwordHash);
        if (!okPass)
            throw new common_1.UnauthorizedException('Invalid credentials');
        const tokens = await this.issueTokens({ sub: user.id, role: user.role });
        return { ...tokens, user: { id: user.id, fullName: user.fullName, role: user.role, studentType: user.role === roles_1.UserRole.STUDENT_OFFLINE ? 'offline' : 'online' } };
    }
    async refresh(refreshToken) {
        try {
            const decoded = await this.jwt.verifyAsync(refreshToken, { secret: this.refreshSecret });
            return this.issueTokens({ sub: decoded.sub, role: decoded.role });
        }
        catch {
            throw new common_1.UnauthorizedException('Invalid refresh token');
        }
    }
    async issueTokens(payload) {
        const accessToken = await this.jwt.signAsync(payload, { secret: this.accessSecret, expiresIn: this.accessExpiresIn });
        const refreshToken = await this.jwt.signAsync(payload, { secret: this.refreshSecret, expiresIn: this.refreshExpiresIn });
        return { accessToken, refreshToken };
    }
};
exports.AuthService = AuthService;
exports.AuthService = AuthService = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [prisma_service_1.PrismaService, jwt_1.JwtService, config_1.ConfigService])
], AuthService);
//# sourceMappingURL=auth.service.js.map