<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class UserCompanyGroupPreference extends Model
{
    protected $fillable = ['username', 'company_group_id', 'hidden_company_ids'];

    protected $casts = [
        'hidden_company_ids' => 'array',
    ];

    public static function hiddenIds(string $username, ?int $companyGroupId): array
    {
        if (!\Illuminate\Support\Facades\Schema::hasTable('user_company_group_preferences')) {
            return [];
        }

        $pref = static::query()
            ->where('username', strtolower($username))
            ->where('company_group_id', $companyGroupId)
            ->first();

        return array_map('intval', $pref?->hidden_company_ids ?? []);
    }

    public static function hide(string $username, ?int $companyGroupId, int $companyId): void
    {
        $pref = static::resolve($username, $companyGroupId);
        $hidden = collect($pref->hidden_company_ids ?? [])
            ->push($companyId)
            ->unique()
            ->values()
            ->all();

        $pref->update(['hidden_company_ids' => $hidden]);
    }

    public static function unhide(string $username, ?int $companyGroupId, int $companyId): void
    {
        $pref = static::resolve($username, $companyGroupId);
        $hidden = collect($pref->hidden_company_ids ?? [])
            ->reject(fn ($id) => (int) $id === $companyId)
            ->values()
            ->all();

        $pref->update(['hidden_company_ids' => $hidden]);
    }

    private static function resolve(string $username, ?int $companyGroupId): self
    {
        return static::firstOrCreate(
            [
                'username'         => strtolower($username),
                'company_group_id' => $companyGroupId,
            ],
            ['hidden_company_ids' => []]
        );
    }
}
