<?php

namespace App\Services\Auth;

use App\Enums\CoachStatus;
use App\Enums\UserRole;
use App\Models\AuditLog;
use App\Models\Athlete;
use App\Models\Coach;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class RegistrationService
{
    public function registerCoach(array $data): User
    {
        return DB::transaction(function () use ($data) {
            $user = User::create([
                'first_name' => $data['first_name'],
                'last_name' => $data['last_name'],
                'mobile' => $data['mobile'],
                'email' => $data['email'] ?? null,
                'password' => Hash::make($data['password']),
                'role' => UserRole::Coach,
                'is_active' => true,
            ]);

            $coach = Coach::create([
                'user_id' => $user->id,
                'status' => CoachStatus::Pending,
            ]);

            AuditLog::record('user.registered', $user, newValues: ['role' => 'coach']);
            AuditLog::record('coach.created_pending', $coach);

            return $user;
        });
    }

    public function registerAthlete(array $data): User
    {
        return DB::transaction(function () use ($data) {
            $user = User::create([
                'first_name' => $data['first_name'],
                'last_name' => $data['last_name'],
                'mobile' => $data['mobile'],
                'email' => $data['email'] ?? null,
                'password' => Hash::make($data['password']),
                'role' => UserRole::Athlete,
                'is_active' => true,
            ]);

            $athlete = Athlete::create([
                'user_id' => $user->id,
            ]);

            AuditLog::record('user.registered', $user, newValues: ['role' => 'athlete']);
            AuditLog::record('athlete.profile_created', $athlete);

            return $user;
        });
    }
}
