<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use App\Models\Concerns\LogsActivity;

class ReturnRequest extends Model
{
    use LogsActivity;

    protected $fillable = [
        'order_id',
        'user_id',
        'status',
        'type',
        'reason',
        'customer_notes',
        'admin_notes',
        'refund_details',
        'refund_amount',
        'refund_method',
        'exchange_order_id',
        'exchange_shipping_cost',
    ];

    protected $casts = [
        'refund_amount' => 'decimal:2',
        'exchange_shipping_cost' => 'decimal:2',
    ];

    public function getActivityLogDescription(string $action): string
    {
        if ($action === 'created') {
            return sprintf('Return request #%s submitted for Order #%s', $this->id, $this->order ? $this->order->order_number : 'N/A');
        }

        if ($action === 'updated') {
            $changes = [];
            if ($this->isDirty('status') || $this->wasChanged('status')) {
                $changes[] = 'status to ' . ucfirst($this->status);
            }
            if (!empty($changes)) {
                return sprintf('Return request #%s updated: %s', $this->id, implode(', ', $changes));
            }
        }

        return sprintf('Return request #%s %s', $this->id, $action);
    }

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

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

    public function items(): HasMany
    {
        return $this->hasMany(ReturnRequestItem::class);
    }

    public function exchangeItems(): HasMany
    {
        return $this->hasMany(ExchangeRequestItem::class, 'return_request_id');
    }

    public function exchangeOrder(): BelongsTo
    {
        return $this->belongsTo(Order::class, 'exchange_order_id');
    }
}
