import { sleep } from '@/utils';
import type {
  AvatarUploadResult,
  CustomerProfile,
  NurseProfile,
  ProfilesApi,
  UpsertCustomerProfileInput,
  UpsertNurseProfileInput,
} from '../types';

const MOCK_LATENCY_MS = 350;

// Both profiles start absent (a fresh user has none — the real GET would 404). Bootstrapping
// via upsert creates them; `isVerified` and the aggregates stay server-owned defaults.
let customerProfile: CustomerProfile | null = null;
let nurseProfile: NurseProfile | null = null;

/**
 * In-memory mock behind the ProfilesApi seam. Mirrors the b3 shapes and keeps the guarded
 * read-only fields (`isVerified=false`, zero aggregates) exactly as the server would, so a
 * bootstrapped nurse is never presented as verified/bookable.
 */
export const profilesMockApi: ProfilesApi = {
  getCustomerProfile: async () => {
    await sleep(MOCK_LATENCY_MS);
    return customerProfile;
  },

  upsertCustomerProfile: async (input: UpsertCustomerProfileInput) => {
    await sleep(MOCK_LATENCY_MS);
    customerProfile = {
      id: customerProfile?.id ?? 1,
      defaultEmergencyContactName: input.defaultEmergencyContactName,
      defaultEmergencyContactPhone: input.defaultEmergencyContactPhone,
      firstName: input.firstName ?? customerProfile?.firstName ?? null,
      lastName: input.lastName ?? customerProfile?.lastName ?? null,
      preferredLanguage: input.preferredLanguage ?? customerProfile?.preferredLanguage ?? null,
    };
    return customerProfile;
  },

  getNurseProfile: async () => {
    await sleep(MOCK_LATENCY_MS);
    return nurseProfile;
  },

  upsertNurseProfile: async (input: UpsertNurseProfileInput) => {
    await sleep(MOCK_LATENCY_MS);
    nurseProfile = {
      id: nurseProfile?.id ?? 1,
      bio: input.bio,
      yearsOfExperience: input.yearsOfExperience,
      educationLevel: input.educationLevel,
      educationField: input.educationField,
      specializationsJson: input.specializationsJson,
      // Server-owned, guarded — a bootstrapped profile is never verified or bookable.
      isVerified: false,
      isAcceptingBookings: nurseProfile?.isAcceptingBookings ?? false,
      averageRating: 0,
      totalReviews: 0,
      totalCompletedBookings: 0,
      avatarUrl: input.avatarUrl ?? nurseProfile?.avatarUrl ?? null,
    };
    return nurseProfile;
  },

  uploadAvatar: async (file: File): Promise<AvatarUploadResult> => {
    await sleep(MOCK_LATENCY_MS);
    // Object URL reflects the actual picked image for the demo; the real impl returns an
    // object-storage URL (REQ-006).
    return { url: URL.createObjectURL(file) };
  },
};
