<?php

namespace App\Models\ProjetosProgramas;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
use DateTimeInterface;

class Anexo extends Model
{
    use HasFactory;

    protected $connection = 'mysql';
    public $incrementing = false;
    protected $keyType = 'string';
    protected $table = 'project_program_attachments';

    const CREATED_AT = 'created_at';
    const UPDATED_AT = 'updated_at';

    protected $fillable = [
        'id',
        'created_at',
        'updated_at',
        'project_id',
        'history_id',
        'name',
        'url',
        'mime',
        'size',
    ];

    public static function boot()
    {
        parent::boot();
        static::creating(function ($model) {
            $model->id = Str::uuid();
        });
    }

    public function projeto()
    {
        return $this->belongsTo(ProjetoPrograma::class, 'project_id');
    }

    public function historico()
    {
        return $this->belongsTo(ProjetoProgramaHistorico::class, 'history_id');
    }

    public function getPublicUrlAttribute(): string
    {
        if (empty($this->url)) {
            return '#';
        }
        $cleanPath = str_replace('\\', '/', $this->url);
        return asset("pmar/assets/files/{$cleanPath}");
    }

    public function getSizeHumanAttribute(): string
    {
        $size = (int) ($this->size ?? 0);
        if ($size >= 1048576) {
            return number_format($size / 1048576, 2, ',', '.') . ' MB';
        }
        if ($size >= 1024) {
            return number_format($size / 1024, 2, ',', '.') . ' KB';
        }
        return $size . ' B';
    }

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }
}
