<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Facades\Storage;

class Wine extends Model
{
    use HasFactory;

    protected $table = 'wines';

    protected $fillable = [
        'vintage',
        'grape_variety_id',
        'alcohol_percentage',
        'bottles_produced',
        'bottling_date',
        'bottles_in_stock',
        'wine_name',
        'price_per_bottle',
        'wine_type',
        'sweetness',
        'description',
        'production_date',
        'status',
        'bottle_volume',
        'image_url',
    ];

    protected $casts = [
        'bottling_date' => 'date',
        'production_date' => 'date',
        'alcohol_percentage' => 'decimal:2',
        'price_per_bottle' => 'decimal:2',
        'bottle_volume' => 'decimal:3',
    ];

    /**
     * Bootstrap the model and its traits.
     */
    protected static function boot()
    {
        parent::boot();

        // Automatically delete the wine image when the wine is deleted
        static::deleting(function ($wine) {
            if ($wine->image_url && Storage::disk('public')->exists($wine->image_url)) {
                Storage::disk('public')->delete($wine->image_url);
            }
        });
    }

    /**
     * Get the grape variety for this wine.
     */
    public function grapeVariety(): BelongsTo
    {
        return $this->belongsTo(GrapeVariety::class, 'grape_variety_id');
    }

    /**
     * Get the wine production records for this wine.
     */
    public function wineProductions(): HasMany
    {
        return $this->hasMany(WineProduction::class, 'wine_id');
    }

    /**
     * Get the harvests used in this wine production (many-to-many through wine_productions).
     */
    public function harvests(): BelongsToMany
    {
        return $this->belongsToMany(Harvest::class, 'wine_productions', 'wine_id', 'harvest_id')
            ->withPivot('consumed_weight', 'blend_percentage')
            ->withTimestamps();
    }
}
