<?php

namespace App\Models;

use App\Enums\PaymentStatus;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Payment extends Model
{
    protected $keyType = 'string';
    public $incrementing = false;

    protected $fillable = [
        'user_id',
        'subscription_id',

        'amount',
        'currency',

        'status',

        'provider',
        'provider_payment_id',

        'invoice_id',
        'billing_reason',
        'attempt_count',

        'paid_at',
    ];

    protected $casts = [
        'paid_at' => 'datetime',
        'status'  => PaymentStatus::class,
    ];

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (!$model->id) {
                $model->id = (string) Str::uuid();
            }
        });
    }

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

    public function subscription()
    {
        return $this->belongsTo(Subscription::class);
    }

    // HELPER
    public function isPaid(): bool
    {
        return $this->status === PaymentStatus::Paid;
    }

    /**
     * Lesbares Label für den Rechnungsgrund.
     * billing_reason in DB kann sein:
     *   - "subscription_create"   → Neues Abonnement
     *   - "subscription_cycle"    → Verlängerung
     *   - "subscription_update"   → Planwechsel (generisch, Fallback)
     *   - "upgrade:Pro"           → Upgrade zu Pro
     *   - "downgrade:Basic"       → Downgrade zu Basic
     *   - "manual"                → Manuelle Zahlung
     */
    public function actionLabel(): string
    {
        $reason = $this->billing_reason ?? '';

        if (str_starts_with($reason, 'upgrade:')) {
            return 'Upgrade zu ' . substr($reason, 8);
        }

        if (str_starts_with($reason, 'downgrade:')) {
            return 'Downgrade zu ' . substr($reason, 10);
        }

        if (str_starts_with($reason, 'refund:')) {
            return 'Erstattung';
        }

        return match ($reason) {
            'subscription_create' => 'Neues Abonnement',
            'subscription_cycle'  => 'Verlängerung',
            'subscription_update' => 'Planwechsel',
            'manual'              => 'Manuelle Zahlung',
            default               => $this->subscription?->plan_name ?? 'Abonnement',
        };
    }
}
