import { upsertProjectSocialAccount } from "@/lib/storage/social-accounts";
import { getPlatformConfig } from "@/lib/social/platforms";
import { ensureProjectForOAuth } from "@/lib/db/assert-project";
import { logAppError } from "@/lib/logging/app-error-logger";
import type { ConnectedAccount } from "@/types/workflow";

export async function persistSocialConnection(
  userId: string,
  projectId: string,
  input: {
    platform: string;
    profileName: string;
    accessToken: string;
    refreshToken?: string | null;
    expiresAt?: string | null;
    externalId?: string | null;
    publishToken?: string | null;
  },
  context?: {
    email?: string;
    name?: string;
    projectName?: string;
    website?: string;
    industry?: string;
    timezone?: string;
  },
): Promise<ConnectedAccount> {
  try {
    // Auto-create a projects row when the browser project has not synced yet
    // (avoids "Project … is not saved on the server yet" during OAuth callback).
    await ensureProjectForOAuth({
      projectId,
      userId,
      email: context?.email,
      name: context?.name,
      projectName: context?.projectName,
      website: context?.website,
      industry: context?.industry,
      timezone: context?.timezone,
    });

    const config = getPlatformConfig(input.platform);
    const now = new Date();

    await upsertProjectSocialAccount(userId, projectId, {
      platform: input.platform,
      label: config?.label ?? input.platform,
      profileName: input.profileName,
      connected: true,
      connectionStatus: "connected",
      accessToken: input.accessToken,
      refreshToken: input.refreshToken ?? null,
      expiresAt: input.expiresAt ?? null,
      externalId: input.externalId ?? null,
      publishToken: input.publishToken ?? null,
      lastSyncedAt: now.toISOString(),
    });

    return {
      platform: input.platform,
      label: config?.label ?? input.platform,
      profileName: input.profileName,
      connected: true,
      connectionStatus: "connected",
      accessToken: input.accessToken,
      refreshToken: input.refreshToken ?? null,
      expiresAt: input.expiresAt ?? null,
      externalId: input.externalId ?? null,
      lastSyncedAt: now.toISOString(),
    };
  } catch (error) {
    await logAppError({
      area: "oauth",
      event: "persist_social_connection_failed",
      projectId,
      platform: input.platform,
      message: `Failed to persist ${input.platform} connection`,
      error,
      details: {
        expiresAt: input.expiresAt ?? null,
        hasPublishToken: Boolean(input.publishToken),
      },
    });
    throw error;
  }
}
