<?php

namespace App\Domain\Financial\Models;

use App\Domain\Financial\Enums\ExpenseCategory;
use App\Domain\Financial\Enums\PaymentMethod;
use App\Domain\Shared\Traits\BelongsToBranch;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Expense extends Model
{
    use HasUuid, BelongsToAcademy, BelongsToBranch, SoftDeletes;

    protected $fillable = [
        'academy_id',
        'branch_id',
        'category',
        'amount',
        'description',
        'recipient_name',
        'payment_method',
        'receipt_reference',
        'expense_date',
        'notes',
        'attachment_path',
        'attachment_name',
        'attachment_disk',
        'attachment_mime',
        'attachment_size',
        'attachment_uploaded_by',
        'attachment_uploaded_at',
        'status',
        'cancelled_by',
        'cancelled_at',
        'cancellation_reason',
        'created_by',
    ];

    protected function casts(): array
    {
        return [
            'category' => ExpenseCategory::class,
            'amount' => 'integer',
            'payment_method' => PaymentMethod::class,
            'expense_date' => 'date',
            'cancelled_at' => 'datetime',
            'attachment_size' => 'integer',
            'attachment_uploaded_at' => 'datetime',
        ];
    }

    public function branch(): BelongsTo
    {
        return $this->belongsTo(\App\Domain\Identity\Models\Branch::class);
    }

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function canceller(): BelongsTo
    {
        return $this->belongsTo(User::class, 'cancelled_by');
    }

    public function attachmentUploader(): BelongsTo
    {
        return $this->belongsTo(User::class, 'attachment_uploaded_by');
    }

    /**
     * Every journal entry this expense produced — the original debit/credit
     * pair and any reversing entry a cancellation added.
     */
    public function transactions(): HasMany
    {
        return $this->hasMany(Transaction::class, 'reference_id')
            ->where('reference_type', static::class);
    }

    public function isCancelled(): bool
    {
        return $this->status === 'cancelled';
    }

    public function hasAttachment(): bool
    {
        return filled($this->attachment_path);
    }

    /**
     * Rows created before the attachment metadata migration landed on the
     * `public` disk; everything since goes to the private one.
     */
    public function attachmentDiskName(): string
    {
        return $this->attachment_disk ?: 'public';
    }

    public function attachmentIsImage(): bool
    {
        return $this->hasAttachment() && str_starts_with((string) $this->attachment_mime, 'image/');
    }

    /**
     * An image an <img> tag can actually paint. HEIC/HEIF is an image and is
     * accepted on upload, but only Safari renders it — everywhere else the
     * page showed a broken picture, so those fall back to the file card.
     */
    public function attachmentIsViewableImage(): bool
    {
        return $this->attachmentIsImage()
            && ! in_array($this->attachment_mime, ['image/heic', 'image/heif', 'image/heic-sequence'], true);
    }

    public function attachmentIsPdf(): bool
    {
        return $this->hasAttachment() && $this->attachment_mime === 'application/pdf';
    }
}
