"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 jwt_1 = require("@nestjs/jwt");
const bcrypt = require("bcrypt");
const business_service_1 = require("../business/business.service");
const email_service_1 = require("../email-sender/email.service");
const users_service_1 = require("../users/users.service");
let AuthService = class AuthService {
    constructor(userService, businessService, emailService, jwtService) {
        this.userService = userService;
        this.businessService = businessService;
        this.emailService = emailService;
        this.jwtService = jwtService;
    }
    async login(loginDto) {
        const user = await this.validateUser(loginDto.email, loginDto.password);
        const token = await this.createToken(user.id, user.businessId);
        console.log(token);
        const userData = await this.userService.findByIdWithBusiness(user.id);
        return {
            access_token: token,
            user: userData
        };
    }
    async registerCompany(registerDto) {
        try {
            const business = await this.createBusiness(registerDto);
            if (!business) {
                throw new common_1.BadRequestException('Failed to setup company');
            }
            const business_admin = await this.createUser({ ...registerDto, role: "business_admin", businessId: business.id });
            const token = await this.createToken(business_admin, "");
            return {
                access_token: token
            };
        }
        catch (error) {
            throw new common_1.BadRequestException('Failed to setup company: ' + error.message);
        }
    }
    async createUser(data) {
        return this.userService.create(data);
    }
    async createBusiness(data) {
        return this.businessService.create(data);
    }
    async validateUser(email, password) {
        const user = await this.userService.findByEmail(email);
        if (!user) {
            throw new common_1.UnauthorizedException('Invalid credentials not found');
        }
        const isPasswordValid = await this.validatePassword(password, user.hashed_password);
        if (!isPasswordValid) {
            throw new common_1.UnauthorizedException('Invalid credentials');
        }
        return user;
    }
    async validatePassword(plainPassword, hashedPassword) {
        return bcrypt.compare(plainPassword, hashedPassword);
    }
    async createToken(id, businessId) {
        const payload = {
            sub: id,
            businessId
        };
        return this.jwtService.sign(payload);
    }
    async validateToken(token) {
        try {
            console.log("validateToken", token);
            const payload = this.jwtService.verify(token);
            console.log("payload", payload);
            const user = await this.userService.findById(payload.sub);
            if (!user) {
                throw new common_1.UnauthorizedException('User not found or inactive');
            }
            return user;
        }
        catch (error) {
            throw new common_1.UnauthorizedException('Invalid token');
        }
    }
    async refreshToken(user) {
        return {
            access_token: await this.createToken(user, ""),
        };
    }
};
exports.AuthService = AuthService;
exports.AuthService = AuthService = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [users_service_1.UsersService,
        business_service_1.BusinessService,
        email_service_1.EmailService,
        jwt_1.JwtService])
], AuthService);
//# sourceMappingURL=auth.service.js.map