<?php

namespace Modules\PortalApi\Http\Controllers\Api;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\PortalApi\Entities\PortalBrand;
use Modules\PortalApi\Entities\PortalOwner;
use Modules\PortalApi\Entities\PortalOwnerToken;

/**
 * Dev-only convenience endpoints so the PWA test-sign-in panel can
 * pre-fill credentials and complete the password flow without anyone
 * needing to know the actual password.
 *
 * ALL endpoints here gate on config('app.debug') and return 404 in
 * production. The router also wraps the whole group with the same
 * gate so even discovery is impossible when debug is off.
 */
class DevAuthController extends Controller
{
    public static function enabled(): bool
    {
        return (bool) env('PORTAL_DEV_LOGIN', false) || config('app.debug');
    }

    /**
     * GET /api/v1/portal/dev/credentials?clinic_slug=...
     *
     * Returns the first active owner of the clinic so the login screen
     * can pre-fill phone + email. Never returns the password — the
     * dev/password endpoint issues a token directly instead.
     */
    public function credentials(Request $request): JsonResponse
    {
        if (! self::enabled()) abort(404);

        $brand = $this->resolveBrand($request->query('clinic_slug'));
        if (! $brand) {
            return response()->json(['message' => 'No active brand resolved.'], 404);
        }

        $owner = PortalOwner::where('business_id', $brand->business_id)
            ->where('is_active', true)
            ->orderBy('id')
            ->first();

        if (! $owner) {
            return response()->json(['message' => 'No owners seeded for this brand.'], 404);
        }

        return response()->json([
            'owner_id'    => $owner->id,
            'name'        => $owner->name,
            'phone'       => $owner->phone,
            'email'       => $owner->email,
            // A placeholder password so the operator can paste anything
            // into the input — the dev/password endpoint accepts it.
            'password'    => 'demo',
            'clinic_slug' => $brand->slug,
        ]);
    }

    /**
     * POST /api/v1/portal/dev/password
     *
     * Issues a real portal bearer for the first active owner of the
     * resolved brand — bypassing the password check entirely. The PWA's
     * test-sign-in panel calls this so the password flow can be exercised
     * end-to-end without anyone needing to know what password was seeded.
     */
    public function password(Request $request): JsonResponse
    {
        if (! self::enabled()) abort(404);

        $brand = $this->resolveBrand($request->input('clinic_slug'));
        if (! $brand) {
            return response()->json(['message' => 'No active brand resolved.'], 404);
        }

        $email = (string) $request->input('email', '');
        $owner = PortalOwner::where('business_id', $brand->business_id)
            ->where('is_active', true)
            ->when($email !== '', fn ($q) => $q->where('email', $email))
            ->orderBy('id')
            ->first();

        if (! $owner) {
            return response()->json(['message' => 'No matching owner.'], 404);
        }

        $token = PortalOwnerToken::issue($owner, $request->userAgent(), $request->ip());

        return response()->json([
            'token' => $token,
            'me'    => [
                'id'    => $owner->id,
                'name'  => $owner->name,
                'phone' => $owner->phone,
                'email' => $owner->email,
            ],
        ]);
    }

    private function resolveBrand(?string $slug): ?PortalBrand
    {
        if ($slug) {
            $b = PortalBrand::where('slug', $slug)->where('is_active', true)->first();
            if ($b) return $b;
        }
        return PortalBrand::where('is_active', true)->orderBy('id')->first();
    }
}
