/**
 * Shopify CP deeplink landing page.
 * Reads one-time code from URL, exchanges for JWT, stores auth, redirects to dashboard.
 *
 * (c) 2026 TWWIM UG. All rights reserved. (www.twwim.com)
 */

import { createFileRoute, useNavigate } from '@tanstack/react-router';
import { z } from 'zod';
import { useEffect, useState } from 'react';
import { AUTH_EXCHANGE_CODE } from '@archer/api-interface/endpoints/customer-api';
import { tokenStorage } from '@/infrastructure/storage/LocalTokenStorage';
import { authenticatedUserStore } from '@/infrastructure/storage/AuthenticatedUserStore';
import { AuthenticatedUserMapper } from '@/infrastructure/http/api/auth/mappers/AuthenticatedUserMapper';

const shopifySearchSchema = z.object({
  code: z.string().length(64),
});

export const Route = createFileRoute('/auth/shopify')({
  validateSearch: shopifySearchSchema,
  component: ShopifyAuthPage,
});

function ShopifyAuthPage() {
  const { code } = Route.useSearch();
  const navigate = useNavigate();
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const exchange = async () => {
      try {
        const baseURL = (import.meta as any).env?.VITE_API_URL || '';
        const res = await fetch(`${baseURL}${AUTH_EXCHANGE_CODE.path}`, {
          method: AUTH_EXCHANGE_CODE.method,
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ code }),
        });

        if (!res.ok) {
          setError('Link expired. Please return to Shopify and try again.');
          return;
        }

        const data = await res.json();

        tokenStorage.setTokens(data.accessToken, data.refreshToken);

        // Code-exchange returns the same TokenResponse shape as /auth/login.
        // fromTokenResponse seeds authOrigin from the JWT itself, so a single
        // call hydrates identity + account.
        try {
          authenticatedUserStore.set(AuthenticatedUserMapper.fromTokenResponse(data));
        } catch {
          /* malformed response — the next navigation will bounce through /login */
        }

        window.history.replaceState({}, '', '/auth/shopify');

        navigate({ to: '/dashboard' });
      } catch {
        setError('Authentication failed. Please return to Shopify and try again.');
      }
    };

    exchange();
  }, [code, navigate]);

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <p className="text-red-600 mb-4">{error}</p>
          <p className="text-gray-500 text-sm">Close this tab and open the dashboard from your Shopify app.</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex items-center justify-center">
      <div className="text-center">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-4" />
        <p className="text-gray-500">Signing you in...</p>
      </div>
    </div>
  );
}
