import { GreenPage } from '../types'; import { createEmptyPage, createNewPage } from './mockDataService'; const USERS_KEY = 'greenpage_users'; const CURRENT_USER_KEY = 'greenpage_currentUser'; // Simulate a database const getDb = () => { try { const db = localStorage.getItem(USERS_KEY); return db ? JSON.parse(db) : {}; } catch (error) { console.error("Error reading from localStorage", error); return {}; } }; const saveDb = (db: any) => { try { localStorage.setItem(USERS_KEY, JSON.stringify(db)); } catch (error) { console.error("Error writing to localStorage", error); } }; export const authService = { register: (email: string, password: string): { success: boolean; message: string } => { const db = getDb(); if (db[email]) { return { success: false, message: 'User with this email already exists.' }; } const initialPage = createNewPage('My First Page'); db[email] = { password, pages: [initialPage] }; saveDb(db); authService.login(email, password); return { success: true, message: 'Registration successful.' }; }, login: (email: string, password: string): { success: boolean; message: string } => { const db = getDb(); const user = db[email]; if (user && user.password === password) { localStorage.setItem(CURRENT_USER_KEY, email); return { success: true, message: 'Login successful.' }; } return { success: false, message: 'Invalid email or password.' }; }, logout: (): void => { localStorage.removeItem(CURRENT_USER_KEY); }, getCurrentUser: (): string | null => { return localStorage.getItem(CURRENT_USER_KEY); }, getUserPages: (): GreenPage[] | null => { const currentUser = authService.getCurrentUser(); if (!currentUser) return null; const db = getDb(); const user = db[currentUser]; if (user && (!user.pages || user.pages.length === 0)) { const initialPage = createNewPage('My First Page'); user.pages = [initialPage]; saveDb(db); } return user ? user.pages : null; }, saveUserPages: (pages: GreenPage[]): void => { const currentUser = authService.getCurrentUser(); if (!currentUser) return; const db = getDb(); if (db[currentUser]) { db[currentUser].pages = pages; saveDb(db); } }, };