"use client";

import type { SyncAdapter } from "@/lib/adapters/sync";
import {
  exportProfileData,
  importProfileData,
  type ProfileExport,
} from "@/lib/profile/db";
import { createClient } from "@/lib/supabase/client";
import { isSupabaseConfigured } from "@/lib/supabase/config";
import {
  migrateLocalProfileToCloud,
  pullCloudMetadataToLocal,
} from "@/lib/oauth/cloudAccount";

/**
 * Cloud metadata sync via Supabase.
 * EmulatorJS save blobs stay local until Storage push/pull is wired (Phase 3).
 */
export class CloudSyncAdapter implements SyncAdapter {
  async exportProfile(profileId: string): Promise<ProfileExport | null> {
    return exportProfileData(profileId);
  }

  async importProfile(data: ProfileExport, asNew = true) {
    return importProfileData(data, asNew);
  }

  async pushSaves(profileId: string) {
    if (!isSupabaseConfigured()) {
      return { ok: false, message: "Supabase is not configured." };
    }
    try {
      const supabase = createClient();
      const {
        data: { user },
      } = await supabase.auth.getUser();
      if (!user) {
        return { ok: false, message: "Sign in with Discord first." };
      }
      const result = await migrateLocalProfileToCloud(user.id, profileId);
      if (!result.ok) return result;
      return {
        ok: true,
        message:
          "Play metadata synced. Emulator save files stay in this browser for now.",
      };
    } catch (e) {
      return {
        ok: false,
        message: e instanceof Error ? e.message : "Sync failed.",
      };
    }
  }

  async pullSaves(profileId: string) {
    if (!isSupabaseConfigured()) {
      return { ok: false, message: "Supabase is not configured." };
    }
    try {
      const supabase = createClient();
      const {
        data: { user },
      } = await supabase.auth.getUser();
      if (!user) {
        return { ok: false, message: "Sign in with Discord first." };
      }
      await pullCloudMetadataToLocal(user.id, profileId);
      return {
        ok: true,
        message:
          "Cloud history, favorites, and achievements pulled into this profile.",
      };
    } catch (e) {
      return {
        ok: false,
        message: e instanceof Error ? e.message : "Pull failed.",
      };
    }
  }
}
