<?php

namespace App\Models\Central;

use App\Models\Tenant\User;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use Stancl\Tenancy\Database\Models\Tenant as BaseTenant;

/**
 * Tenant model — extends Stancl Tenant for compatibility with the package
 * (so we can use stancl helpers later if we want to switch to multi-DB).
 *
 * In single-DB mode we don't use HasDatabase. Domain identification is
 * handled by our own ResolveTenant middleware (slug-based, not DNS records).
 */
class Company extends BaseTenant implements HasMedia
{
    use InteractsWithMedia, SoftDeletes;

    protected $table = 'companies';

    public $incrementing = true;

    protected $guarded = [];

    protected $casts = [
        'settings' => 'array',
        'data' => 'array',
        'trial_ends_at' => 'datetime',
        'active_until' => 'datetime',
    ];

    /** Stancl expects this to know what columns are NOT in the JSON `data` blob. */
    public static function getCustomColumns(): array
    {
        return [
            'id',
            'slug', 'name', 'display_name', 'city', 'phone', 'email', 'contact_name',
            'status', 'plan_id', 'is_demo', 'default_warehouse_id',
            'trial_ends_at', 'active_until',
            'settings',
            'created_at', 'updated_at', 'deleted_at',
        ];
    }

    public function plan()
    {
        return $this->belongsTo(Plan::class);
    }

    public function users()
    {
        return $this->hasMany(User::class);
    }

    public function subscriptions()
    {
        return $this->hasMany(Subscription::class);
    }

    public function latestSubscription()
    {
        return $this->hasOne(Subscription::class)->latestOfMany('period_end');
    }

    public function isActive(): bool
    {
        return in_array($this->status, ['active', 'trial'], true);
    }

    public function isAccessible(): bool
    {
        if ($this->status === 'archived' || $this->status === 'suspended') {
            return false;
        }
        if ($this->status === 'expired') {
            return false;
        }
        return true;
    }

    /** Get the URL for this tenant. */
    public function url(?string $path = '/'): string
    {
        $central = config('app.central_domain') ?: 'service.mir.md';
        return "https://{$this->slug}.{$central}{$path}";
    }

    public function registerMediaCollections(): void
    {
        $this->addMediaCollection('logo')->singleFile();
        $this->addMediaCollection('favicon')->singleFile();
    }

    public function getLogoUrl(): ?string
    {
        $m = $this->getFirstMedia('logo');
        if (! $m) return null;
        // Validate file actually exists on disk (storage may be ephemeral
        // and DB row may point to lost file from previous deploy).
        if (! @file_exists($m->getPath())) return null;
        return $m->getUrl();
    }

    public function getFaviconUrl(): ?string
    {
        $m = $this->getFirstMedia('favicon');
        if (! $m) return null;
        if (! @file_exists($m->getPath())) return null;
        return $m->getUrl();
    }
}
