import {
  ConflictException,
  ForbiddenException,
  Inject,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import * as bcrypt from 'bcrypt';
import { normalizeEmail, normalizeRequiredString } from '../common/utils/normalize.js';
import { APP_CONFIG, type AppConfig } from '../config/app.config.js';
import { PrismaService } from '../prisma/prisma.service.js';
import type { LoginDto } from './dto/login.dto.js';
import type { RegisterDto } from './dto/register.dto.js';
import type {
  AuthTokensResponse,
  JwtPayload,
  SafeUser,
} from './types/auth.types.js';

@Injectable()
export class AuthService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly jwtService: JwtService,
    @Inject(APP_CONFIG) private readonly config: AppConfig,
  ) {}

  async register(dto: RegisterDto): Promise<SafeUser> {
    if (!this.config.allowPublicRegistration) {
      throw new ForbiddenException(
        'Public registration is disabled. Ask an administrator to provision your account.',
      );
    }

    return this.createUser({
      firstName: dto.firstName,
      lastName: dto.lastName,
      email: dto.email,
      password: dto.password,
      role: 'SALES_USER',
      isActive: true,
    });
  }

  async createUser(input: {
    firstName: string;
    lastName: string;
    email: string;
    password: string;
    role: SafeUser['role'];
    isActive?: boolean;
  }): Promise<SafeUser> {
    const email = normalizeEmail(input.email);

    const existing = await this.prisma.db.orm.public.User.where((u) =>
      u.email.eq(email),
    ).first();

    if (existing) {
      throw new ConflictException('Email is already registered');
    }

    const passwordHash = await bcrypt.hash(
      input.password,
      this.config.bcryptRounds,
    );

    return this.prisma.db.orm.public.User.select(
      'id',
      'firstName',
      'lastName',
      'email',
      'role',
      'isActive',
      'createdAt',
      'updatedAt',
    ).create({
      firstName: normalizeRequiredString(input.firstName),
      lastName: normalizeRequiredString(input.lastName),
      email,
      passwordHash,
      role: input.role,
      isActive: input.isActive ?? true,
    });
  }

  async login(dto: LoginDto): Promise<AuthTokensResponse> {
    const email = normalizeEmail(dto.email);

    const user = await this.prisma.db.orm.public.User.where((u) =>
      u.email.eq(email),
    ).first();

    if (!user || !user.isActive) {
      throw new UnauthorizedException('Invalid credentials');
    }

    const passwordMatches = await bcrypt.compare(
      dto.password,
      user.passwordHash,
    );

    if (!passwordMatches) {
      throw new UnauthorizedException('Invalid credentials');
    }

    const safeUser = this.toSafeUser(user);
    const accessToken = await this.signAccessToken(safeUser);

    return {
      accessToken,
      user: safeUser,
    };
  }

  async findActiveSafeUserById(id: string): Promise<SafeUser | null> {
    const user = await this.prisma.db.orm.public.User.select(
      'id',
      'firstName',
      'lastName',
      'email',
      'role',
      'isActive',
      'createdAt',
      'updatedAt',
    )
      .where((u) => u.id.eq(id))
      .first();

    if (!user || !user.isActive) {
      return null;
    }

    return user;
  }

  private async signAccessToken(user: SafeUser): Promise<string> {
    const payload: JwtPayload = {
      sub: user.id,
      email: user.email,
      role: user.role,
    };

    return this.jwtService.signAsync(payload);
  }

  private toSafeUser(user: {
    id: string;
    firstName: string;
    lastName: string;
    email: string;
    role: SafeUser['role'];
    isActive: boolean;
    createdAt: Date;
    updatedAt: Date;
  }): SafeUser {
    return {
      id: user.id,
      firstName: user.firstName,
      lastName: user.lastName,
      email: user.email,
      role: user.role,
      isActive: user.isActive,
      createdAt: user.createdAt,
      updatedAt: user.updatedAt,
    };
  }
}
