<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Automation;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AutomationController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $user  = $request->user();
        $isPro = $user->isInternalUser() || $user->hasFeature('automations');
        $types = config('automations.types', []);

        \Log::info('Automation index', [
            'user_id'    => $user->id,
            'plan_key'   => $user->subscription?->plan?->key ?? 'none',
            'is_pro'     => $isPro,
            'free_types' => config('automations.free_types', []),
        ]);

        $userAutomations = $user->automations()->get()->keyBy('type');

        $locale = $user->locale ?? 'de';

        $result = collect($types)
            ->map(function (array $def, string $type) use ($userAutomations, $isPro, $locale) {
                $userAuto  = $userAutomations->get($type);
                $isFree    = (bool) ($def['is_free'] ?? false);
                $name      = t("automations.type.{$type}.name", [], $locale);
                $desc      = t("automations.type.{$type}.description", [], $locale);
                return [
                    'type'            => $type,
                    'name'            => ($name !== "automations.type.{$type}.name") ? $name : $def['name'],
                    'description'     => ($desc !== "automations.type.{$type}.description") ? $desc : $def['description'],
                    'icon'            => $def['icon_app'],
                    'color'           => $def['color_hex'],
                    'is_free'         => $isFree,
                    'is_active'       => $userAuto?->active ?? false,
                    'is_configured'   => $userAuto !== null,
                    'available'       => $isFree || $isPro,
                    'channels'        => $def['channels'] ?? ['push'],
                    'settings'        => $userAuto?->config ?? $def['defaults'],
                    'settings_schema' => collect($def['defaults'])
                        ->except(['channel', 'weekdays_only'])
                        ->toArray(),
                ];
            })
            ->values();

        return response()->json([
            'success' => true,
            'data'    => $result,
        ]);
    }

    public function update(Request $request, string $type): JsonResponse
    {
        $types = config('automations.types');
        if (!isset($types[$type])) {
            return response()->json(['success' => false, 'message' => 'Unbekannter Typ.'], 422);
        }

        $user  = $request->user();
        $def   = $types[$type];
        $isPro = $user->isInternalUser() || $user->hasFeature('automations');

        if (!$def['is_free'] && !$isPro) {
            return response()->json(['success' => false, 'message' => 'Pro erforderlich.'], 403);
        }

        $config    = array_merge($def['defaults'], $request->input('settings', []));
        $is_active = $request->boolean('is_active', true);

        $user->automations()->updateOrCreate(
            ['type' => $type],
            ['name' => $def['name'], 'active' => $is_active, 'config' => $config]
        );

        return response()->json(['success' => true]);
    }

    public function toggle(Request $request, string $type): JsonResponse
    {
        $types = config('automations.types');
        if (!isset($types[$type])) {
            return response()->json(['success' => false, 'message' => 'Unbekannter Typ.'], 404);
        }

        $user  = $request->user();
        $def   = $types[$type];
        $isPro = $user->isInternalUser() || $user->hasFeature('automations');

        if (!(bool) ($def['is_free'] ?? false) && !$isPro) {
            return response()->json(['success' => false, 'message' => 'Pro erforderlich.'], 403);
        }

        $request->validate(['is_active' => 'boolean']);

        $automation = $user->automations()->firstOrCreate(
            ['type' => $type],
            ['name' => $def['name'], 'active' => false, 'config' => $def['defaults']]
        );

        $newActive = $request->has('is_active')
            ? $request->boolean('is_active')
            : !$automation->active;

        $automation->update(['active' => $newActive]);

        return response()->json([
            'success' => true,
            'data'    => ['type' => $type, 'is_active' => $automation->active],
        ]);
    }

    public function destroy(Request $request, string $type): JsonResponse
    {
        $request->user()->automations()->where('type', $type)->delete();
        return response()->json(['success' => true]);
    }
}
