<?php

declare(strict_types=1);

namespace App\Models;

use App\Models\Traits\BelongsToTenant;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * @property string $id
 * @property string $tenant_id
 * @property string $slug
 * @property string $name
 * @property string|null $description
 * @property string|null $group_name
 * @property string $skin
 * @property string $perms_read
 * @property string $perms_write
 * @property string $perms_comment
 * @property string $perms_download
 * @property bool $is_active
 * @property int $post_count
 * @property int $sort_order
 */
class Board extends Model
{
    use BelongsToTenant;
    use HasFactory;
    use HasUuids;

    protected $fillable = [
        'tenant_id', 'slug', 'name', 'description', 'group_name',
        'skin', 'perms_read', 'perms_write', 'perms_comment', 'perms_download',
        'is_active', 'post_count', 'sort_order',
    ];

    protected function casts(): array
    {
        return [
            'is_active' => 'boolean',
            'post_count' => 'integer',
            'sort_order' => 'integer',
        ];
    }

    public function posts(): HasMany
    {
        return $this->hasMany(Post::class);
    }

    public function categories(): HasMany
    {
        return $this->hasMany(BoardCategory::class)->orderBy('sort_order');
    }

    /**
     * 권한 레벨 비교: guest < member < admin
     */
    public static function permLevel(string $perm): int
    {
        return match ($perm) {
            'guest' => 0,
            'member' => 1,
            'admin' => 2,
            default => 99,
        };
    }

    public function canRead(?User $user): bool
    {
        return $this->checkPerm($this->perms_read, $user);
    }

    public function canWrite(?User $user): bool
    {
        return $this->checkPerm($this->perms_write, $user);
    }

    public function canComment(?User $user): bool
    {
        return $this->checkPerm($this->perms_comment, $user);
    }

    public function canDownload(?User $user): bool
    {
        return $this->checkPerm($this->perms_download, $user);
    }

    protected function checkPerm(string $required, ?User $user): bool
    {
        $needed = self::permLevel($required);
        if ($needed === 0) return true; // guest
        if ($user === null) return false;
        $userLevel = $user->hasRole('admin') ? 2 : 1;
        return $userLevel >= $needed;
    }
}
