<?php

use App\Http\Controllers\Api\AgentChatController;
use App\Http\Controllers\Api\AuthController;
use App\Http\Controllers\Api\AutomationController;
use App\Http\Controllers\Api\DashboardController;
use App\Http\Controllers\Api\DeviceController;
use App\Http\Controllers\Api\EventController;
use App\Http\Controllers\Api\ContactController;
use App\Http\Controllers\Api\NoteController;
use App\Http\Controllers\Api\SettingsController;
use App\Http\Controllers\Api\TaskController;
use App\Http\Controllers\Api\TranslationController;
use App\Http\Controllers\Stripe\WebhookController;
use App\Http\Controllers\Webhooks\GoogleCalendarWebhookController;

// Webhooks — kein Auth, kein CSRF (von externen Diensten kommend)
Route::post('/stripe/webhook', WebhookController::class)
    ->name('stripe.webhook');

Route::post('/webhooks/google-calendar', GoogleCalendarWebhookController::class)
    ->name('webhooks.google-calendar');

Route::prefix('v1')->group(function () {

    // Translations — öffentlich, kein Auth
    Route::get('/translations/{locale}', [TranslationController::class, 'index']);

    // Version — öffentlich, kein Auth
    Route::get('/version/current', function (\Illuminate\Http\Request $request) {
        $platform = $request->query('platform', 'web');
        $version  = \App\Models\AppVersion::current($platform);

        return response()->json([
            'success' => true,
            'data'    => $version ? [
                'version'     => $version->version,
                'name'        => $version->name,
                'changelog'   => $version->changelog,
                'status'      => $version->status,
                'show_popup'  => $version->show_popup,
                'released_at' => $version->released_at,
            ] : null,
        ]);
    });

    // Auth — Login ohne Token
    Route::post('/auth/login', [AuthController::class, 'login']);

    // Geschützte API-Routen — Bearer Token oder Session erforderlich
    Route::middleware('auth.custom')->group(function () {

        // Auth
        Route::post('/auth/logout', [AuthController::class, 'logout']);
        Route::get('/auth/me', [AuthController::class, 'me']);

        // Kalender
        Route::get('/events', [EventController::class, 'index']);
        Route::post('/events', [EventController::class, 'store']);
        Route::put('/events/{id}', [EventController::class, 'update']);
        Route::delete('/events/{id}', [EventController::class, 'destroy']);

        // Aufgaben
        Route::get('/tasks', [TaskController::class, 'index']);
        Route::post('/tasks', [TaskController::class, 'store']);
        Route::put('/tasks/{id}', [TaskController::class, 'update']);
        Route::delete('/tasks/{id}', [TaskController::class, 'destroy']);

        // Kontakte
        Route::get('/contacts', [ContactController::class, 'index']);
        Route::post('/contacts', [ContactController::class, 'store']);
        Route::put('/contacts/{id}', [ContactController::class, 'update']);
        Route::delete('/contacts/{id}', [ContactController::class, 'destroy']);

        // Notizen
        Route::get('/notes', [NoteController::class, 'index']);
        Route::post('/notes', [NoteController::class, 'store']);
        Route::put('/notes/{id}', [NoteController::class, 'update']);
        Route::delete('/notes/{id}', [NoteController::class, 'destroy']);

        // Aria Agent
        Route::post('/agent/chat', [AgentChatController::class, 'chat']);
        Route::post('/agent/synthesize', [AgentChatController::class, 'synthesize']);
        Route::get('/agent/logs', [AgentChatController::class, 'logs']);

        // Einstellungen
        Route::get('/settings/credits', [SettingsController::class, 'credits']);
        Route::get('/settings/affiliate', [SettingsController::class, 'affiliate']);
        Route::put('/settings/profile', [SettingsController::class, 'updateProfile']);
        Route::put('/settings/password', [SettingsController::class, 'updatePassword']);
        Route::delete('/settings/account', [SettingsController::class, 'deleteAccount']);
        Route::get('/settings/notifications', [SettingsController::class, 'notificationSettings']);
        Route::put('/settings/notifications', [SettingsController::class, 'notificationSettings']);

        // Automationen
        Route::get('/automations', [AutomationController::class, 'index']);
        Route::post('/automations/{type}/toggle', [AutomationController::class, 'toggle']);
        Route::put('/automations/{type}', [AutomationController::class, 'update']);
        Route::delete('/automations/{type}', [AutomationController::class, 'destroy']);

        // Dashboard
        Route::get('/dashboard/birthdays', [DashboardController::class, 'birthdays']);

        // In-App Notifications
        Route::get('/notifications/unread', function () {
            $userId = auth()->id();
            $notifications = \App\Models\Notification::where('user_id', $userId)
                ->latest()
                ->take(15)
                ->get();
            return response()->json([
                'success' => true,
                'data' => [
                    'notifications' => $notifications,
                    'count' => \App\Models\Notification::where('user_id', $userId)->whereNull('read_at')->count(),
                ],
            ]);
        });
        Route::post('/notifications/read-all', function () {
            \App\Models\Notification::where('user_id', auth()->id())
                ->whereNull('read_at')
                ->update(['read_at' => now()]);
            return response()->json(['success' => true]);
        });
        Route::post('/notifications/{id}/read', function (string $id) {
            \App\Models\Notification::where('user_id', auth()->id())
                ->where('id', $id)
                ->update(['read_at' => now()]);
            return response()->json(['success' => true]);
        });
        Route::delete('/notifications/read', function () {
            \App\Models\Notification::where('user_id', auth()->id())
                ->whereNotNull('read_at')
                ->delete();
            return response()->json(['success' => true]);
        });
        Route::delete('/notifications', function () {
            \App\Models\Notification::where('user_id', auth()->id())->delete();
            return response()->json(['success' => true]);
        });
        Route::delete('/notifications/{id}', function (string $id) {
            \App\Models\Notification::where('user_id', auth()->id())
                ->where('id', $id)
                ->delete();
            return response()->json(['success' => true]);
        });

        // Push Notifications / Geräte
        Route::post('/devices/register', [DeviceController::class, 'register']);
        Route::put('/devices/{device_id}/token', [DeviceController::class, 'updateToken']);
        Route::delete('/devices/{device_id}/token', [DeviceController::class, 'deactivateToken']);
        Route::delete('/devices/{device_id}', [DeviceController::class, 'destroy']);
    });

});

// Fallback — fängt alle nicht definierten Routen auf api.aziros.com ab
Route::fallback(function () {
    return response()->json([
        'success' => false,
        'message' => 'Not Found',
    ], 404);
});
