<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class AiUsage extends Model
{
    protected $table = 'ai_usage';

    protected $fillable = [
        'tenant_id',
        'user_id',
        'period_start',
        'provider_key',
        'model',
        'prompt_tokens',
        'completion_tokens',
        'total_tokens',
    ];

    protected $casts = [
        'period_start' => 'date',
    ];

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Record a spend row for the given user. Resolves the period_start from
     * the owner's active subscription window (billing-period anchor) or falls
     * back to the first day of the current calendar month.
     */
    public static function record(
        User $user,
        string $providerKey,
        string $model,
        int $promptTokens,
        int $completionTokens,
    ): self {
        $tenant = $user->tenant;
        $periodStart = self::resolvePeriodStart($tenant);

        return static::create([
            'tenant_id'         => $tenant?->id,
            'user_id'           => $user->id,
            'period_start'      => $periodStart->toDateString(),
            'provider_key'      => $providerKey,
            'model'             => $model,
            'prompt_tokens'     => $promptTokens,
            'completion_tokens' => $completionTokens,
            'total_tokens'      => $promptTokens + $completionTokens,
        ]);
    }

    /**
     * Resolve the billing-period anchor for a tenant. Uses the workspace
     * owner's active subscription start, falling back to the current
     * calendar month's first day (self-hosted / no subscription).
     */
    public static function resolvePeriodStart(?Tenant $tenant): Carbon
    {
        if ($tenant === null) {
            return Carbon::now()->startOfMonth();
        }

        $owner = $tenant->owner()->first();
        if ($owner) {
            $sub = $owner->activeSubscription();
            if ($sub && $sub->current_period_starts_at) {
                return Carbon::parse($sub->current_period_starts_at)->startOfDay();
            }
        }

        return Carbon::now()->startOfMonth();
    }
}
