<?php

namespace App\Models\Central;

use App\Models\Tenant\User;
use Illuminate\Database\Eloquent\SoftDeletes;
use Stancl\Tenancy\Database\Models\Tenant as BaseTenant;
use Stancl\Tenancy\Contracts\TenantWithDatabase;
use Stancl\Tenancy\Database\Concerns\HasDatabase;
use Stancl\Tenancy\Database\Concerns\HasDomains;

/**
 * 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
{
    use 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',
            '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 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}";
    }
}
