<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Stancl\Tenancy\Database\Concerns\CentralConnection;

class ExternalServiceUsage extends Model
{
    use CentralConnection;

    protected $table = 'external_service_usage';

    protected $fillable = [
        'tenant_id',
        'service',
        'section',
        'hits',
        'created_at',
    ];

    protected static function boot(): void
    {
        parent::boot();

        static::creating(fn($model) => $model->created_at = now()->startOfDay());
    }

    /**
     * Increment usage for a specific service and section.
     */
    public function logUsage(string $tenantId, string $service, string $section): void
    {
        $usage = static::query()->firstOrNew([
            'tenant_id' => $tenantId,
            'service' => $service,
            'section' => $section,
            'created_at' => now()->startOfDay()
        ]);

        $usage->hits++;
        $usage->save();
    }
}
