<?php

namespace App\Services\Experiments;

use Illuminate\Support\Facades\DB;

class ExperimentService
{
    public function getAssignment(int $userId, string $experimentKey): ?string
    {
        $exp = DB::table('experiments')->where('key', $experimentKey)->first();
        if (!$exp) return null;
        $assign = DB::table('experiment_assignments')
            ->where('user_id', $userId)->where('experiment_id', $exp->id)->first();
        return $assign?->variant_key;
    }

    public function assignIfMissing(int $userId, string $experimentKey): ?string
    {
        $exp = DB::table('experiments')->where('key', $experimentKey)->first();
        if (!$exp) return null;
        $existing = DB::table('experiment_assignments')
            ->where('user_id', $userId)->where('experiment_id', $exp->id)->first();
        if ($existing) return $existing->variant_key;
        $variants = json_decode($exp->variant_keys, true) ?: [];
        if (!$variants) return null;
        // Stable assignment using hash(userId + experimentKey)
        $hash = crc32($userId . '|' . $experimentKey);
        $variant = $variants[$hash % count($variants)];
        DB::table('experiment_assignments')->insert([
            'user_id' => $userId,
            'experiment_id' => $exp->id,
            'variant_key' => $variant,
            'assigned_at' => now(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);
        return $variant;
    }
}
