<?php

namespace Licenzo\Model;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

use Licenzo\Casts\MoneyCast;
use Licenzo\Framework\Database\Model;
use Licenzo\Services\Integrations\ProviderAliasService;

class SubscriptionProduct extends Model
{
    protected $table = 'licenzo_subscription_products';

    protected $fillable = [
        'subscription_id', 'product_id', 'variation_id',
        'provider', 'provider_id',
        'product_name', 'variation_name', 'currency', 'price', 'quantity',
        'product_data', 'variation_data'
    ];

    protected $casts = [
        'id' => 'int',
        'subscription_id' => 'int',
        'product_id' => 'int',
        'variation_id' => 'int',
        'provider' => 'string',
        'provider_id' => 'string',
        'currency' => 'string',
        'price' => MoneyCast::class,
        'quantity' => 'int',
        'product_data' => 'array',
        'variation_data' => 'array',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    public function setProviderAttribute($value)
    {
        $this->attributes['provider'] = ProviderAliasService::normalize((string) $value, Product::PROVIDER_MANUAL);
    }

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

    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    public function variation()
    {
        return $this->belongsTo(ProductVariation::class, 'variation_id');
    }

    // Helpers
    public function getProductSnapshot(): array
    {
        return $this->product_data ?? [];
    }

    public function getVariationSnapshot(): array
    {
        return $this->variation_data ?? [];
    }

    public function getTotalPrice(): float
    {
        return $this->price * $this->quantity;
    }
}
