<?php

namespace App\Domain\Training\Services;

use App\Domain\Shared\Exceptions\DomainException;
use App\Domain\Training\Models\Activity;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class ActivityService
{
    public function create(array $data, User $actor): Activity
    {
        return DB::transaction(function () use ($data, $actor) {
            $slug = Str::limit($data['slug'] ?? Str::slug($data['name']), 90, '');

            // Check slug uniqueness within academy
            $exists = Activity::where('slug', $slug)->exists();
            if ($exists) {
                $slug = Str::limit($slug, 85, '') . '-' . Str::random(4);
            }

            return Activity::create([
                'name' => $data['name'],
                'name_ar' => $data['name_ar'],
                'slug' => $slug,
                'description' => $data['description'] ?? null,
                'description_ar' => $data['description_ar'] ?? null,
                'icon' => $data['icon'] ?? null,
                'color' => $data['color'] ?? null,
                'category' => $data['category'] ?? 'sport',
                'is_active' => $data['is_active'] ?? true,
                'sort_order' => $data['sort_order'] ?? 0,
                'metadata' => $data['metadata'] ?? [],
            ]);
        });
    }

    public function update(Activity $activity, array $data): Activity
    {
        return DB::transaction(function () use ($activity, $data) {
            if (isset($data['slug']) && $data['slug'] !== $activity->slug) {
                $exists = Activity::where('slug', $data['slug'])
                    ->where('id', '!=', $activity->id)
                    ->exists();
                if ($exists) {
                    throw new DomainException('هذا المعرف مستخدم بالفعل');
                }
            }

            $activity->update($data);
            return $activity->fresh();
        });
    }

    public function delete(Activity $activity): void
    {
        DB::transaction(function () use ($activity) {
            // Check if activity has participants
            if ($activity->participants()->exists()) {
                throw new DomainException('لا يمكن حذف نشاط مرتبط بمشتركين');
            }

            $activity->delete();
        });
    }

    public function toggleActive(Activity $activity): Activity
    {
        $activity->update(['is_active' => !$activity->is_active]);
        return $activity->fresh();
    }
}
