<?php
declare(strict_types=1);

namespace App\Modules\SportsActivity\Services;

use App\Core\App;
use App\Core\EventBus;
use App\Modules\SportsActivity\SaConstants;

final class GroupTransferService
{
    public static function transfer(int $playerId, int $fromGroupId, int $toGroupId, string $reason = ''): array
    {
        $db = App::getInstance()->db();

        if ($fromGroupId === $toGroupId) {
            return ['success' => false, 'error' => 'لا يمكن النقل لنفس المجموعة'];
        }

        $db->beginTransaction();
        try {
            $enrollment = $db->selectOne(
                "SELECT id FROM sa_group_players WHERE group_id = ? AND player_id = ? AND status = ?",
                [$fromGroupId, $playerId, SaConstants::STATUS_ACTIVE]
            );
            if (!$enrollment) {
                $db->rollBack();
                return ['success' => false, 'error' => 'اللاعب غير مسجل في المجموعة المصدر'];
            }

            $toGroup = $db->selectOne(
                "SELECT current_count, max_capacity FROM sa_groups WHERE id = ? AND status = ? AND is_archived = 0 FOR UPDATE",
                [$toGroupId, SaConstants::GROUP_ACTIVE]
            );
            if (!$toGroup) {
                $db->rollBack();
                return ['success' => false, 'error' => 'المجموعة المستهدفة غير موجودة أو غير نشطة'];
            }

            if ((int) $toGroup['current_count'] >= (int) $toGroup['max_capacity']) {
                $db->rollBack();
                return ['success' => false, 'error' => 'المجموعة المستهدفة ممتلئة'];
            }

            $fromGroup = $db->selectOne(
                "SELECT current_count FROM sa_groups WHERE id = ? FOR UPDATE",
                [$fromGroupId]
            );

            $employeeId = (int) (App::getInstance()->session()->get('employee_id') ?? 0);
            $now = date('Y-m-d H:i:s');

            $db->update('sa_group_players', [
                'status'                  => SaConstants::STATUS_TRANSFERRED,
                'left_at'                 => date('Y-m-d'),
                'transferred_to_group_id' => $toGroupId,
                'transfer_reason'         => $reason ?: null,
                'updated_at'              => $now,
            ], 'id = ?', [(int) $enrollment['id']]);

            $newEnrollmentId = $db->insert('sa_group_players', [
                'group_id'    => $toGroupId,
                'player_id'   => $playerId,
                'enrolled_at' => date('Y-m-d'),
                'status'      => SaConstants::STATUS_ACTIVE,
                'created_at'  => $now,
                'updated_at'  => $now,
                'created_by'  => $employeeId,
            ]);

            $newFromCount = max(0, (int) $fromGroup['current_count'] - 1);
            $db->update('sa_groups', [
                'current_count' => $newFromCount,
                'is_full'       => 0,
                'updated_at'    => $now,
            ], 'id = ?', [$fromGroupId]);

            $newToCount = (int) $toGroup['current_count'] + 1;
            $db->update('sa_groups', [
                'current_count' => $newToCount,
                'is_full'       => $newToCount >= (int) $toGroup['max_capacity'] ? 1 : 0,
                'updated_at'    => $now,
            ], 'id = ?', [$toGroupId]);

            $db->commit();

            EventBus::dispatch('sa.player.transferred', [
                'player_id'       => $playerId,
                'from_group_id'   => $fromGroupId,
                'to_group_id'     => $toGroupId,
                'enrollment_id'   => $newEnrollmentId,
                'reason'          => $reason,
            ]);

            return [
                'success'       => true,
                'enrollment_id' => $newEnrollmentId,
            ];
        } catch (\Throwable $e) {
            $db->rollBack();
            return ['success' => false, 'error' => 'فشل عملية النقل: ' . $e->getMessage()];
        }
    }
}
