import { Injectable, NotFoundException, UnauthorizedException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { License } from '../../entities/license.entity';
import { randomBytes } from 'crypto';

@Injectable()
export class LicensesService {
  constructor(
    @InjectRepository(License)
    private licenseRepository: Repository<License>,
  ) {}

  async findById(id: string, userId?: string, isSuperAdmin?: boolean): Promise<License> {
    const license = await this.licenseRepository.findOne({
      where: { id },
      relations: ['owner'],
    });

    if (!license) {
      throw new NotFoundException('License not found');
    }

    // Check authorization: must be owner or super admin
    if (!isSuperAdmin && userId && license.owner_user_id !== userId) {
      throw new UnauthorizedException('You do not have access to this license');
    }

    return license;
  }

  async findByKey(licenseKey: string): Promise<License | null> {
    return this.licenseRepository.findOne({
      where: { license_key: licenseKey },
      relations: ['owner'],
    });
  }

  async findByOwner(ownerId: string): Promise<License[]> {
    return this.licenseRepository.find({
      where: { owner_user_id: ownerId },
      order: { created_at: 'DESC' },
    });
  }

  async create(ownerId: string): Promise<License> {
    const licenseKey = this.generateLicenseKey();
    const license = this.licenseRepository.create({
      license_key: licenseKey,
      owner_user_id: ownerId,
      status: 'active',
      modules_enabled: [],
      webstore_active: false,
    });

    return this.licenseRepository.save(license);
  }

  async validateKey(licenseKey: string) {
    const license = await this.findByKey(licenseKey);

    if (!license) {
      throw new NotFoundException('License key not found');
    }

    return {
      valid: license.status === 'active',
      license: {
        id: license.id,
        license_key: license.license_key,
        status: license.status,
        server_name: license.server_name,
        subdomain: license.subdomain,
        modules_enabled: license.modules_enabled,
        webstore_active: license.webstore_active,
        created_at: license.created_at,
        expires_at: license.expires_at,
      },
    };
  }

  private generateLicenseKey(): string {
    const part1 = randomBytes(2).toString('hex').toUpperCase();
    const part2 = randomBytes(2).toString('hex').toUpperCase();
    const part3 = randomBytes(2).toString('hex').toUpperCase();
    return `CORR-${part1}-${part2}-${part3}`;
  }
}
