<?php

namespace App\Services\Users;

use App\Models\ParentModel;
use Illuminate\Support\Facades\DB;

class InactiveUserCleanupService
{
    public function cleanup(int $minutes = 15): array
    {
        $cutoff = now()->subMinutes($minutes)->toDateTimeString();

        $users = DB::table('users')
            ->select('id')
            ->where('status', 'Inactive')
            ->where('created_at', '<', $cutoff)
            ->get()
            ->map(fn ($row) => (array) $row)
            ->all();

        if (empty($users)) {
            $orphans = $this->purgeOrphanedUserRoles();
            return [
                'deleted_users' => 0,
                'deleted_parents' => 0,
                'deleted_roles' => $orphans,
            ];
        }

        $userIds = array_map(static fn ($u) => (int) ($u['id'] ?? 0), $users);
        $userIds = array_values(array_filter($userIds));

        $deletedParents = 0;
        DB::transaction(function () use ($userIds, &$deletedParents): void {
            $deletedParents = ParentModel::query()
                ->whereIn('firstparent_id', $userIds)
                ->delete();

            DB::table('user_roles')->whereIn('user_id', $userIds)->delete();
            DB::table('users')->whereIn('id', $userIds)->delete();
        });

        $orphans = $this->purgeOrphanedUserRoles();

        return [
            'deleted_users' => count($userIds),
            'deleted_parents' => (int) $deletedParents,
            'deleted_roles' => $orphans,
        ];
    }

    private function purgeOrphanedUserRoles(): int
    {
        return DB::table('user_roles')
            ->whereNotIn('user_id', function ($q) {
                $q->select('id')->from('users');
            })
            ->delete();
    }
}
