<?php

namespace App\Models;

use App\Enums\ModuleType;
use Illuminate\Support\Str;
use App\Models\Traits\Filterable;
use App\Enums\AttachmentContentType;
use App\Models\Traits\SelectOptions;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Attachment extends Model
{
  use HasFactory, Filterable, SelectOptions;

  protected $fillable = [
    'transaction_id',
    'payment_id',
    'module_type',
    'type',
    'label',
    'value',
    'description',
    'path',
  ];

  protected $casts = [
    'module_type' => ModuleType::class,
    'type' => AttachmentContentType::class,
  ];

  protected static function booted()
  {
    static::created(function ($attachment) {
      if (Str::startsWith($attachment->value, "/files/")) {
        $encodedId = base64_encode($attachment->id);
        $attachment->value .= $encodedId;
        $attachment->saveQuietly();
      }
    });
  }

  public function transaction()
  {
    return $this->belongsTo(Transaction::class, 'transaction_id');
  }

  public function payment()
  {
    return $this->belongsTo(Payment::class, 'payment_id');
  }
}
