import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import * as bcrypt from 'bcryptjs';
import { Usuario } from '../users/entities/usuario.entity';
import { Perfil } from '../users/entities/perfil.entity';

@Injectable()
export class AuthService {
  constructor(
    @InjectRepository(Usuario) private userRepo: Repository<Usuario>,
    @InjectRepository(Perfil) private perfilRepo: Repository<Perfil>,
    private jwtService: JwtService,
  ) {}

  async login(email: string, senha: string) {
    const user = await this.userRepo.findOne({
      where: { email, ativo: true },
      relations: ['perfil'],
    });
    if (!user) throw new UnauthorizedException('Credenciais inválidas');

    const valid = await bcrypt.compare(senha, user.senha_hash);
    if (!valid) throw new UnauthorizedException('Credenciais inválidas');

    user.ultimo_acesso = new Date();
    await this.userRepo.save(user);

    const payload = {
      sub: user.id,
      email: user.email,
      nome: user.nome,
      perfil_id: user.perfil_id,
      perfil_nome: user.perfil.nome,
    };

    return {
      access_token: this.jwtService.sign(payload),
      user: {
        id: user.id,
        nome: user.nome,
        email: user.email,
        perfil: user.perfil.nome,
        perfil_id: user.perfil_id,
      },
    };
  }

  async me(userId: string) {
    const user = await this.userRepo.findOne({
      where: { id: userId },
      relations: ['perfil'],
    });
    return {
      id: user.id,
      nome: user.nome,
      email: user.email,
      perfil: user.perfil.nome,
      perfil_id: user.perfil_id,
    };
  }
}
