import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { Address, Order, User } from '@/domain/entities';
import { AuthDomainService, RegisterInput } from '@/domain/services/AuthDomainService';
import { IAuthRepository } from '@/application/ports/IAuthRepository';
import { DEMO_EMAIL } from '@/lib/constants';
import { DEMO_ORDERS } from '@/infrastructure/data/demo-orders.data';

interface AuthState {
  user: User | null;
  orders: Order[];
  isAuthenticated: boolean;
}

interface AuthInternalActions {
  _patch: (patch: Partial<AuthState>) => void;
}

const DEMO_USER: User = {
  id: 'demo-1',
  name: 'Ahmed Khan',
  email: DEMO_EMAIL,
  phone: '+46 72 585 50 50',
  address: {
    street: 'Tingvallavägen 11',
    city: 'Märsta',
    state: 'Stockholm',
    zip: '195 31',
  },
  createdAt: '2025-03-15T10:00:00.000Z',
};

export const useAuthStore = create<AuthState & AuthInternalActions>()(
  persist(
    (set) => ({
      user: null,
      orders: [],
      isAuthenticated: false,
      _patch: (patch) => set(patch),
    }),
    { name: 'kott-gard-auth' }
  )
);

export class ZustandAuthRepository implements IAuthRepository {
  private getState() {
    return useAuthStore.getState();
  }

  getUser(): User | null {
    return this.getState().user;
  }

  getOrders(): Order[] {
    return this.getState().orders;
  }

  isAuthenticated(): boolean {
    return this.getState().isAuthenticated;
  }

  login(email: string, password: string): boolean {
    const state = this.getState();

    if (
      email === DEMO_EMAIL &&
      AuthDomainService.isDemoCredentials(email, password)
    ) {
      state._patch({
        user: DEMO_USER,
        isAuthenticated: true,
        orders:
          state.orders.length > 0 ? state.orders : DEMO_ORDERS,
      });
      return true;
    }

    if (AuthDomainService.emailMatchesStoredUser(state.user, email)) {
      state._patch({ isAuthenticated: true });
      return true;
    }

    return false;
  }

  register(data: RegisterInput): boolean {
    const user = AuthDomainService.createUser(data);
    this.getState()._patch({ user, isAuthenticated: true });
    return true;
  }

  logout(): void {
    this.getState()._patch({ isAuthenticated: false });
  }

  updateProfile(data: Partial<User>): void {
    const current = this.getState().user;
    if (current) {
      this.getState()._patch({ user: { ...current, ...data } });
    }
  }

  addOrder(order: Order): void {
    const orders = this.getState().orders;
    this.getState()._patch({ orders: [order, ...orders] });
  }
}