<?php

namespace App\Http\Middleware;

use App\Models\AppBuilder;
use App\Models\SystemSetting;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class ValidateBuilderAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Get server_key from URL path parameter
        $serverKey = $request->route('server_key');

        if (! $serverKey) {
            return response()->json([
                'error' => 'Server key is required',
            ], 401);
        }

        // First check regular (non-default) builders by stored server_key
        $builder = AppBuilder::where('server_key', $serverKey)
            ->where('is_default', false)
            ->first();

        // If not found, check if this is the default builder's purchase code or demo code
        if (! $builder) {
            $purchaseCode = SystemSetting::get('purchase_code');
            $demoCode = config('app.demo') ? config('app.demo_code') : null;

            if (($purchaseCode && $serverKey === $purchaseCode) ||
                ($demoCode && $serverKey === $demoCode)) {
                $builder = AppBuilder::where('is_default', true)->first();
            }
        }

        if (! $builder) {
            return response()->json([
                'error' => 'Invalid server key',
            ], 401);
        }

        // Attach builder to request for use in controllers
        $request->attributes->set('app_builder', $builder);

        return $next($request);
    }
}
