<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Address extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'name',
        'mobile',
        'line1',
        'line2',
        'country_id',
        'state_id',
        'city_id',
        'city',
        'state',
        'pin',
        'is_default',
    ];

    protected function casts(): array
    {
        return [
            'is_default' => 'boolean',
        ];
    }

    public function country()
    {
        return $this->belongsTo(Country::class);
    }

    public function stateRelation()
    {
        return $this->belongsTo(State::class, 'state_id');
    }

    public function cityRelation()
    {
        return $this->belongsTo(City::class, 'city_id');
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function getFullAddressAttribute(): string
    {
        $city = $this->cityRelation?->name ?? $this->city;
        $state = $this->stateRelation?->name ?? $this->state;
        $country = $this->country?->name;

        $parts = array_filter([
            $this->line1,
            $this->line2,
            $city,
            $state,
            $this->pin,
            $country,
        ]);

        return implode(', ', $parts);
    }
}
