<?php

namespace App\Models;

use App\enum\DomainType;
use App\enum\ProviderType;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Domain extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'name',
        'is_active',
        'daily_mailbox_limit',
        'domain_type',
        'provider_type',
        'starts_at',
        'ends_at',
        'last_used_at',
        'checked_at',
    ];

    protected function casts(): array
    {
        return [
            'is_active' => 'boolean',
            'daily_mailbox_limit' => 'integer',
            'starts_at' => 'datetime',
            'ends_at' => 'datetime',
            'last_used_at' => 'datetime',
            'checked_at' => 'datetime',
        ];
    }

    /**
     * Retrieve active domains by type and provider.
     *
     * @param  DomainType|null  $domainType  Filter by domain type
     * @param  ProviderType|null  $providerType  Filter by provider type
     * @return array Array of domain names
     */
    public static function getActiveDomainsByType(
        ?DomainType $domainType = null,
        ?ProviderType $providerType = null
    ): array {
        $query = static::query()
            ->where('is_active', true)
            ->where(function ($query) {
                $query->whereNull('starts_at')
                    ->orWhere('starts_at', '<=', now());
            })
            ->where(function ($query) {
                $query->whereNull('ends_at')
                    ->orWhere('ends_at', '>=', now());
            });

        if ($domainType) {
            $query->where('domain_type', $domainType->value);
        }

        if ($providerType) {
            $query->where('provider_type', $providerType->value);
        }

        return $query->pluck('name')->toArray();
    }

    /**
     * Retrieve all active domains grouped by type.
     *
     * @return array Array with 'domains' and 'premium_domains' keys
     */
    public static function getActiveDomains(): array
    {
        $domains = static::query()
            ->where('is_active', true)
            ->where(function ($query) {
                $query->whereNull('starts_at')
                    ->orWhere('starts_at', '<=', now());
            })
            ->where(function ($query) {
                $query->whereNull('ends_at')
                    ->orWhere('ends_at', '>=', now());
            })
            ->select('name', 'domain_type')
            ->get()
            ->groupBy('domain_type');

        return [
            'domains' => $domains->get(DomainType::PUBLIC->value, collect())->pluck('name')->toArray(),
            'premium_domains' => $domains->get(DomainType::PREMIUM->value, collect())->pluck('name')->toArray(),
        ];
    }
}
