import { Injectable, Inject, NotFoundException, ConflictException } from '@nestjs/common';
import { ISSUER_REPOSITORY, IIssuerRepository } from '../../domain/repositories/issuer.repository.interface';
import { IssuerStatus } from '../../domain/entities/issuer.entity';

@Injectable()
export class IssuerService {
  constructor(
    @Inject(ISSUER_REPOSITORY)
    private readonly issuerRepo: IIssuerRepository,
  ) {}

  async register(
    userId: string,
    data: {
      companyName: string;
      contactName: string;
      contactPhone: string;
      contactEmail?: string;
      businessLicense?: string;
      description?: string;
      logoUrl?: string;
    },
  ) {
    const existing = await this.issuerRepo.findByUserId(userId);
    if (existing) throw new ConflictException('User already registered as issuer');

    return this.issuerRepo.create({
      userId,
      ...data,
      status: IssuerStatus.PENDING,
    });
  }

  async findById(id: string) {
    const issuer = await this.issuerRepo.findById(id);
    if (!issuer) throw new NotFoundException('Issuer not found');
    return issuer;
  }

  async findByUserId(userId: string) {
    return this.issuerRepo.findByUserId(userId);
  }

  async approve(id: string) {
    await this.issuerRepo.updateStatus(id, IssuerStatus.ACTIVE);
  }

  async reject(id: string) {
    await this.issuerRepo.updateStatus(id, IssuerStatus.REJECTED);
  }

  async listAll(page: number, limit: number, status?: string) {
    const [items, total] = await this.issuerRepo.findAndCount({
      status,
      page,
      limit,
    });
    return { items, total, page, limit };
  }
}
