import { Injectable } from '@nestjs/common';
import { UserService } from '../user/user.service';
import { JwtService } from '@nestjs/jwt';
import { User } from '../user/user.entity';
import { SafeUser } from '../user/dto/user-safe.dto';

@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private jwtService: JwtService,
  ) { }

  async validateUser(username: string, pass: string): Promise<User | null> {
    const user = await this.userService.findOneByUsername(username);
    if (user && (await user.validatePassword(pass))) {
      return user;
    }
    return null;
  }

  async login(user: SafeUser) {
    const payload = {
      username: user.username,
      sub: user.id,
      role: user.role,
      tenantId: user.tenantId
    };
    return {
      access_token: this.jwtService.sign(payload),
      user: {
        id: user.id,
        username: user.username,
        role: user.role,
        tenantId: user.tenantId,
        displayName: user.displayName
      }
    };
  }

  async getOrCreateApiKey(userId: string) {
    return this.userService.getOrCreateApiKey(userId);
  }

  async regenerateApiKey(userId: string) {
    return this.userService.regenerateApiKey(userId);
  }
}
