import { Injectable, Inject, NotFoundException } from '@nestjs/common';
import { Refund, RefundStatus } from '../../domain/entities/refund.entity';
import {
  REFUND_REPOSITORY,
  IRefundRepository,
} from '../../domain/repositories/refund.repository.interface';
import { SettlementAmount } from '../../domain/value-objects/settlement-amount.vo';

@Injectable()
export class RefundService {
  constructor(
    @Inject(REFUND_REPOSITORY)
    private readonly refundRepo: IRefundRepository,
  ) {}

  async createRefund(data: {
    orderId: string;
    userId: string;
    amount: string;
    reason: string;
  }): Promise<Refund> {
    // Validate amount using VO
    SettlementAmount.create(data.amount);

    return this.refundRepo.create({
      orderId: data.orderId,
      userId: data.userId,
      amount: data.amount,
      reason: data.reason,
      status: RefundStatus.PENDING,
    });
  }

  async approveRefund(id: string, processedBy: string): Promise<void> {
    await this.refundRepo.update(id, {
      status: RefundStatus.APPROVED,
      processedBy,
      processedAt: new Date(),
    });
  }

  async completeRefund(id: string): Promise<void> {
    await this.refundRepo.update(id, { status: RefundStatus.COMPLETED });
  }

  async rejectRefund(id: string, processedBy: string): Promise<void> {
    await this.refundRepo.update(id, {
      status: RefundStatus.REJECTED,
      processedBy,
      processedAt: new Date(),
    });
  }

  async listRefunds(
    page: number,
    limit: number,
    status?: string,
  ): Promise<{ items: Refund[]; total: number; page: number; limit: number }> {
    const [items, total] = await this.refundRepo.findAndCount({
      status: status as RefundStatus | undefined,
      page,
      limit,
    });
    return { items, total, page, limit };
  }
}
