<?php

namespace App\Models;

use App\Services\Reports\ReportTemplateDefaults;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class ReportTemplate extends Model
{
    use HasFactory;

    protected $fillable = [
        'client_id',
        'brand_kit_id',
        'name',
        'description',
        'type',
        'channels',
        'sections',
        'settings',
        'is_default',
        'is_active',
        'sort_order',
    ];

    protected $casts = [
        'channels' => 'array',
        'sections' => 'array',
        'settings' => 'array',
        'is_default' => 'boolean',
        'is_active' => 'boolean',
        'sort_order' => 'integer',
    ];

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

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

    public function schedules(): HasMany
    {
        return $this->hasMany(ReportSchedule::class, 'report_template_id');
    }

    public function generatedReports(): HasMany
    {
        return $this->hasMany(GeneratedReport::class, 'report_template_id');
    }

    public function enabledSections(): array
    {
        return app(ReportTemplateDefaults::class)->sectionsFor($this);
    }

    public function effectiveSettings(?Client $client = null): array
    {
        return app(ReportTemplateDefaults::class)->settingsFor($this, $client ?: $this->client);
    }

    public function effectiveChannels(): array
    {
        return app(ReportTemplateDefaults::class)->normalizeChannels($this->channels ?: []);
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }
}
