<?php

namespace App\Services;

use App\Models\Module;
use App\Models\SchoolModule;
use Illuminate\Support\Facades\DB;

class ModuleEntitlementService
{
    public function schoolHasModule(int $schoolId, string $moduleKey): bool
    {
        return SchoolModule::query()
            ->where('school_id', $schoolId)
            ->where('enabled', true)
            ->whereHas('module', fn ($query) => $query->where('key_name', $moduleKey)->where('status', 'active'))
            ->where(function ($query): void {
                $query->whereNull('starts_at')->orWhere('starts_at', '<=', now()->toDateString());
            })
            ->where(function ($query): void {
                $query->whereNull('expires_at')->orWhere('expires_at', '>=', now()->toDateString());
            })
            ->exists();
    }

    public function enableModule(int $schoolId, string $moduleKey, ?int $userId = null): void
    {
        $module = Module::query()->where('key_name', $moduleKey)->firstOrFail();

        DB::transaction(function () use ($schoolId, $module, $userId): void {
            SchoolModule::query()->updateOrCreate(
                ['school_id' => $schoolId, 'module_id' => $module->id],
                ['enabled' => true, 'enabled_by' => $userId]
            );
        });
    }
}
