// ── Auth Context ──────────────────────────────────────────────
// Provides authentication state and actions for ChronoMind web.
// Delegates to @bytelyst/react-auth shared package.

'use client';

import { createAuthProvider } from '@bytelyst/react-auth';
import { setSyncEnabled } from './platform-sync';
import { PRODUCT_ID, getAuthClient } from './auth-api';

interface ChronoMindUser {
  id: string;
  email: string;
  name: string;
  displayName: string;
  role: string;
  plan: string;
  [key: string]: unknown;
}

function getBaseUrl(): string {
  if (typeof window !== 'undefined' && (window as unknown as Record<string, unknown>).__PLATFORM_URL__) {
    return (window as unknown as Record<string, unknown>).__PLATFORM_URL__ as string;
  }
  return process.env.NEXT_PUBLIC_PLATFORM_SERVICE_URL ?? 'https://api.chronomind.app';
}

const { AuthProvider: _AuthProvider, useAuth: _useAuth } = createAuthProvider<ChronoMindUser>({
  baseUrl: getBaseUrl(),
  storagePrefix: 'chronomind',
  loginEndpoint: '/auth/login',
  registerEndpoint: '/auth/register',
  forgotPasswordEndpoint: '/auth/forgot-password',
  changePasswordEndpoint: '/auth/change-password',
  deleteAccountEndpoint: '/auth/account',
  refreshEndpoint: '/auth/refresh',
  mapLoginResponse: (data: unknown) => {
    const d = data as { user: { id: string; email: string; displayName: string; role: string; plan: string }; accessToken: string; refreshToken: string };
    setSyncEnabled(true);
    return {
      user: { id: d.user.id, email: d.user.email, name: d.user.displayName, displayName: d.user.displayName, role: d.user.role, plan: d.user.plan },
      accessToken: d.accessToken,
      refreshToken: d.refreshToken,
    };
  },
  onLogout: () => setSyncEnabled(false),
});

export const AuthProvider = _AuthProvider;

/**
 * Wrapper around shared useAuth that adapts naming for backward compat:
 * - success → successMessage
 * - clearMessages → clearError
 */
export function useAuth() {
  const ctx = _useAuth();
  return {
    ...ctx,
    successMessage: ctx.success,
    clearError: ctx.clearMessages,
    resetPassword: async (token: string, newPassword: string): Promise<boolean> => {
      try {
        await getAuthClient().resetPassword(token, newPassword);
        return true;
      } catch {
        return false;
      }
    },
  };
}

export type { ChronoMindUser as AuthUser };
