<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Storage;

class GeneratedReport extends Model
{
    use HasFactory;

    protected $fillable = [
        'client_id',
        'report_template_id',
        'report_schedule_id',
        'report_type',
        'channels',
        'date_from',
        'date_to',
        'status',
        'summary',
        'ai_status',
        'ai_provider',
        'ai_executive_summary',
        'ai_customer_note',
        'ai_technical_note',
        'ai_risks',
        'ai_opportunities',
        'ai_actions',
        'ai_raw_response',
        'ai_error_message',
        'ai_generated_at',
        'html_path',
        'pdf_path',
        'excel_path',
        'csv_path',
        'sent_at',
        'generated_at',
        'generated_by',
        'error_message',
    ];

    protected $casts = [
        'channels' => 'array',
        'date_from' => 'date',
        'date_to' => 'date',
        'summary' => 'array',
        'ai_risks' => 'array',
        'ai_opportunities' => 'array',
        'ai_actions' => 'array',
        'ai_generated_at' => 'datetime',
        'sent_at' => 'datetime',
        'generated_at' => 'datetime',
    ];

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

    public function template(): BelongsTo
    {
        return $this->belongsTo(ReportTemplate::class, 'report_template_id');
    }

    public function schedule(): BelongsTo
    {
        return $this->belongsTo(ReportSchedule::class, 'report_schedule_id');
    }

    public function emailLogs(): HasMany
    {
        return $this->hasMany(EmailLog::class, 'generated_report_id');
    }

    public function fileExists(?string $path): bool
    {
        return $path !== null && Storage::disk('public')->exists($path);
    }

    public function hasAiInsights(): bool
    {
        return $this->ai_status === 'completed' && filled($this->ai_executive_summary);
    }
}
