<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Schema;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    protected static array $columnExistsCache = [];
    private const DEFAULT_SUPER_ADMIN_EMAILS = [
        'ogwubenvic18@gmail.com',
    ];

    protected $fillable = [
        'name', 'email', 'password', 'role', 'is_super_admin', 'department', 'category', 'client_api_key_id',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'is_super_admin' => 'boolean',
        ];
    }

    public static function hasColumn(string $column): bool
    {
        if (!array_key_exists($column, self::$columnExistsCache)) {
            self::$columnExistsCache[$column] = Schema::hasColumn('users', $column);
        }

        return self::$columnExistsCache[$column];
    }

    public static function supportDeskSelectColumns(array $extra = []): array
    {
        $columns = ['id', 'name', 'email'];

        foreach (['role', 'department', 'category', 'is_super_admin', 'client_api_key_id', 'created_at'] as $optional) {
            if (self::hasColumn($optional)) {
                $columns[] = $optional;
            }
        }

        foreach ($extra as $column) {
            if (!in_array($column, $columns, true) && self::hasColumn($column)) {
                $columns[] = $column;
            }
        }

        return $columns;
    }

    public static function configuredSuperAdminEmails(): array
    {
        $configured = array_filter(array_map(
            static fn ($email) => strtolower(trim((string) $email)),
            explode(',', (string) env('SUPER_ADMIN_EMAILS', ''))
        ));

        return array_values(array_unique([
            ...self::DEFAULT_SUPER_ADMIN_EMAILS,
            ...$configured,
        ]));
    }

    public function supportDeskIsSuperAdmin(): bool
    {
        if ((bool) ($this->is_super_admin ?? false)) {
            return true;
        }

        return in_array(strtolower((string) $this->email), self::configuredSuperAdminEmails(), true);
    }

    public function supportDeskRole(): string
    {
        return $this->supportDeskIsSuperAdmin() ? 'admin' : (string) ($this->role ?? 'user');
    }

    public function requestedTickets()
    {
        return $this->hasMany(Ticket::class, 'requester_id');
    }

    public function assignedTickets()
    {
        return $this->hasMany(Ticket::class, 'assigned_to_id');
    }

    public function comments()
    {
        return $this->hasMany(Comment::class, 'author_id');
    }

    public function clientApiKey()
    {
        return $this->belongsTo(ClientApiKey::class, 'client_api_key_id');
    }
}
