<?php

namespace App\Modules\Admin\Billing\Repositories;

use App\Modules\Admin\Billing\Models\Invoice;
use App\Modules\Admin\Tenancy\Models\Subscription;

class InvoiceRepository
{
    public function createDraftForSubscription(Subscription $subscription): Invoice
    {
        $tenantId = (int) $subscription->tenant_id;
        $number = 'INV-'.$tenantId.'-'.(int) $subscription->id.'-'.time();

        return Invoice::query()->create([
            'tenant_id' => $tenantId,
            'subscription_id' => (int) $subscription->id,
            'number' => $number,
            'amount' => (string) ($subscription->plan?->price ?? 0),
            'currency' => (string) ($subscription->plan?->currency ?? 'USD'),
            'status' => Invoice::STATUS_DRAFT,
            'period_start' => $subscription->starts_at?->toDateString(),
            'period_end' => $subscription->ends_at?->toDateString(),
            'meta' => ['source' => 'subscription_renewal'],
        ]);
    }

    public function countOpenForTenant(int $tenantId): int
    {
        return Invoice::query()
            ->where('tenant_id', $tenantId)
            ->whereIn('status', [Invoice::STATUS_DRAFT, Invoice::STATUS_OPEN])
            ->count();
    }
}
