import {
  Injectable,
  ConflictException,
  UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import * as bcrypt from 'bcryptjs';
import { UsersService } from '../users/users.service';
import { RegisterDto } from './dto/register.dto';
import { LoginDto } from './dto/login.dto';

@Injectable()
export class AuthService {
  constructor(
    private readonly usersService: UsersService,
    private readonly jwtService: JwtService,
  ) {}

  async register(dto: RegisterDto) {
    const existing = await this.usersService.findByUsername(dto.username);
    if (existing) throw new ConflictException('Användarnamnet är redan taget');

    const passwordHash = await bcrypt.hash(dto.password, 12);
    const user = await this.usersService.create({
      username: dto.username,
      email: dto.email,
      passwordHash,
    });

    return this.issueToken(user.id, user.username, user.role, user.isPremium);
  }

  async login(dto: LoginDto) {
    const user = await this.usersService.findByUsername(dto.username);
    if (!user) throw new UnauthorizedException('Felaktigt användarnamn eller lösenord');

    const valid = await bcrypt.compare(dto.password, user.passwordHash);
    if (!valid) throw new UnauthorizedException('Felaktigt användarnamn eller lösenord');

    return this.issueToken(user.id, user.username, user.role, user.isPremium);
  }

  private issueToken(userId: number, username: string, role: string, isPremium: boolean) {
    const payload = { sub: userId, username, role, isPremium };
    return {
      accessToken: this.jwtService.sign(payload),
      userId,
      username,
      role,
      isPremium,
    };
  }
}
