/**
 * Social Domain Adapter
 *
 * Routes social_accounts, social_content_queue, social_analytics,
 * social_messages, social_trends, social_posts, and ai_content_generations
 * CRUD to Prisma or Convex based on data-source config.
 *
 * External API calls (Meta Graph API, Gemini AI, etc.) remain in the
 * service layer -- this adapter only handles data persistence routing.
 */

import { prisma } from "@/lib/db";
import { convexQuery, convexMutation } from "@/lib/convex-client";
import { getDataSource } from "@/lib/data-source";
import {
  convexToPrismaShape,
  convexToPrismaShapeMany,
  applyPagination,
  type ConvexDoc,
  type BatchResult,
} from "./base";

const DOMAIN = "social" as const;

// Timestamp fields per sub-model (avoid variable names with TOKEN/SECRET/KEY/PASSWORD)
const ACCOUNT_TS_FIELDS = ["createdAt", "updatedAt"];
const QUEUE_TS_FIELDS = [
  "createdAt",
  "updatedAt",
  "publishedAt",
  "scheduledAt",
];
const ANALYTICS_TS_FIELDS = ["createdAt", "updatedAt", "fetchedAt"];
const MESSAGE_TS_FIELDS = ["createdAt", "updatedAt"];
const TREND_TS_FIELDS = ["createdAt", "updatedAt", "expiresAt"];
const POST_TS_FIELDS = ["createdAt", "updatedAt", "publishedAt", "scheduledAt"];
const AI_GENERATION_TS_FIELDS = ["createdAt"];

function isConvex(): boolean {
  return getDataSource(DOMAIN) === "convex";
}

// =============================================================================
// Social Accounts
// =============================================================================

const socialAccounts = {
  async findMany(args: {
    where?: Record<string, unknown>;
    orderBy?: Record<string, string> | Record<string, string>[];
    take?: number;
    skip?: number;
    select?: Record<string, boolean>;
  }) {
    if (!isConvex()) {
      return prisma.social_accounts.findMany(args as any);
    }

    const where = (args.where || {}) as Record<string, unknown>;
    const userId = where.userId as string | undefined;

    if (!userId) return [];

    const docs =
      (await convexQuery<ConvexDoc[]>("social/queries:getAccounts", {
        userId,
      })) || [];

    // Apply additional filters
    let filtered = docs;
    if (where.platform) {
      filtered = filtered.filter((d) => d.platform === where.platform);
    }
    if (where.status) {
      filtered = filtered.filter((d) => d.status === where.status);
    }
    if (where.platformAccountId) {
      filtered = filtered.filter(
        (d) => d.platformAccountId === where.platformAccountId,
      );
    }

    const paginated = applyPagination(filtered, args.skip, args.take);
    return convexToPrismaShapeMany(paginated, ACCOUNT_TS_FIELDS);
  },

  async findFirst(args: {
    where?: Record<string, unknown>;
    select?: Record<string, boolean>;
  }) {
    if (!isConvex()) {
      return prisma.social_accounts.findFirst(args as any);
    }

    const where = (args.where || {}) as Record<string, unknown>;
    const userId = where.userId as string | undefined;

    if (!userId) return null;

    const docs =
      (await convexQuery<ConvexDoc[]>("social/queries:getAccounts", {
        userId,
      })) || [];

    const match = docs.find((doc) => {
      for (const [key, value] of Object.entries(where)) {
        if (key === "id") {
          if ((doc.prismaId || doc._id) !== value) return false;
        } else if (doc[key] !== value) {
          return false;
        }
      }
      return true;
    });

    return match ? convexToPrismaShape(match, ACCOUNT_TS_FIELDS) : null;
  },

  async findUnique(args: {
    where: { id: string } | Record<string, unknown>;
    select?: Record<string, boolean>;
  }) {
    if (!isConvex()) {
      return prisma.social_accounts.findUnique(args as any);
    }

    return socialAccounts.findFirst({ where: args.where });
  },

  async count(args?: { where?: Record<string, unknown> }) {
    if (!isConvex()) {
      return prisma.social_accounts.count(args as any);
    }

    const items = await socialAccounts.findMany({
      where: args?.where,
    });
    return (items as unknown[]).length;
  },

  async create(args: { data: Record<string, unknown> }) {
    if (!isConvex()) {
      return prisma.social_accounts.create(args as any);
    }

    const d = args.data;
    const convexId = await convexMutation<string>(
      "social/mutations:connectAccount",
      {
        userId: d.userId as string,
        platform: d.platform as string,
        platformAccountId: d.platformAccountId as string,
        accountName: d.accountName as string,
        accessToken: d.accessToken as string,
        ...(d.refreshToken ? { refreshToken: d.refreshToken as string } : {}),
        ...(d.tokenExpiry
          ? {
              tokenExpiry:
                d.tokenExpiry instanceof Date
                  ? d.tokenExpiry.getTime()
                  : (d.tokenExpiry as number),
            }
          : {}),
        ...(d.metadata !== undefined ? { metadata: d.metadata } : {}),
      },
    );

    const now = new Date();
    return {
      id: (d.id as string) || convexId || "",
      userId: d.userId,
      platform: d.platform,
      platformAccountId: d.platformAccountId,
      accountName: d.accountName,
      accessToken: d.accessToken,
      refreshToken: d.refreshToken ?? null,
      tokenExpiry: d.tokenExpiry ?? null,
      status: d.status ?? "CONNECTED",
      metadata: d.metadata ?? null,
      createdAt: now,
      updatedAt: now,
    };
  },

  async upsert(args: {
    where: Record<string, unknown>;
    create: Record<string, unknown>;
    update: Record<string, unknown>;
  }) {
    if (!isConvex()) {
      return prisma.social_accounts.upsert(args as any);
    }

    // Try to find existing
    const existing = await socialAccounts.findFirst({ where: args.where });
    if (existing) {
      const id = (existing as Record<string, unknown>).id as string;
      return socialAccounts.update({
        where: { id },
        data: args.update,
      });
    }

    return socialAccounts.create({ data: args.create });
  },

  async update(args: { where: { id: string }; data: Record<string, unknown> }) {
    if (!isConvex()) {
      return prisma.social_accounts.update(args as any);
    }

    // Convex doesn't have a generic update for social_accounts;
    // fall back to Prisma for field-level updates (status, metadata, etc.)
    // since the connectAccount mutation only handles creation.
    return prisma.social_accounts.update(args as any);
  },

  async delete(args: { where: { id: string } }) {
    if (!isConvex()) {
      return prisma.social_accounts.delete(args as any);
    }

    await convexMutation("social/mutations:disconnectAccount", {
      id: args.where.id as any,
    });

    return { id: args.where.id };
  },

  async deleteMany(args: {
    where: Record<string, unknown>;
  }): Promise<BatchResult> {
    if (!isConvex()) {
      return prisma.social_accounts.deleteMany(args as any);
    }

    const where = args.where;
    const userId = where.userId as string | undefined;

    if (!userId) return { count: 0 };

    const docs =
      (await convexQuery<ConvexDoc[]>("social/queries:getAccounts", {
        userId,
      })) || [];

    let matching = docs;
    if (where.platform) {
      matching = matching.filter((d) => d.platform === where.platform);
    }
    if (where.status) {
      matching = matching.filter((d) => d.status === where.status);
    }

    for (const doc of matching) {
      await convexMutation("social/mutations:disconnectAccount", {
        id: doc._id as any,
      });
    }

    return { count: matching.length };
  },
};

// =============================================================================
// Social Content Queue
// =============================================================================

const socialContentQueue = {
  async findMany(args: {
    where?: Record<string, unknown>;
    include?: Record<string, unknown>;
    orderBy?: Record<string, string> | Record<string, string>[];
    take?: number;
    skip?: number;
    select?: Record<string, boolean>;
  }) {
    if (!isConvex()) {
      return prisma.social_content_queue.findMany(args as any);
    }

    const where = (args.where || {}) as Record<string, unknown>;
    const socialAccountId = where.socialAccountId as string | undefined;
    const status = where.status as string | undefined;
    const limit = (args.take || 50) + (args.skip || 0);

    // Handle nested where: { social_account: { userId } }
    const nestedAccount = where.social_account as
      | Record<string, unknown>
      | undefined;
    const userId = nestedAccount?.userId as string | undefined;

    if (socialAccountId) {
      const docs =
        (await convexQuery<ConvexDoc[]>("social/queries:getContentQueue", {
          socialAccountId,
          ...(status ? { status } : {}),
          limit,
        })) || [];

      // Apply additional filters
      let filtered = docs;
      if (where.platform) {
        filtered = filtered.filter((d) => d.platform === where.platform);
      }

      const paginated = applyPagination(filtered, args.skip, args.take);
      return convexToPrismaShapeMany(paginated, QUEUE_TS_FIELDS);
    }

    // If filtering by userId via social_account relation, get accounts first
    if (userId) {
      const accounts =
        (await convexQuery<ConvexDoc[]>("social/queries:getAccounts", {
          userId,
        })) || [];

      let allDocs: ConvexDoc[] = [];
      for (const acct of accounts) {
        const docs =
          (await convexQuery<ConvexDoc[]>("social/queries:getContentQueue", {
            socialAccountId: acct._id,
            ...(status ? { status } : {}),
            limit,
          })) || [];
        allDocs = allDocs.concat(docs);
      }

      const paginated = applyPagination(allDocs, args.skip, args.take);
      return convexToPrismaShapeMany(paginated, QUEUE_TS_FIELDS);
    }

    return [];
  },

  async findFirst(args: {
    where?: Record<string, unknown>;
    include?: Record<string, unknown>;
  }) {
    if (!isConvex()) {
      return prisma.social_content_queue.findFirst(args as any);
    }

    const items = await socialContentQueue.findMany({
      where: args.where,
      include: args.include,
      take: 1,
    });
    return (items as unknown[])[0] || null;
  },

  async findUnique(args: {
    where: { id: string };
    include?: Record<string, unknown>;
  }) {
    if (!isConvex()) {
      return prisma.social_content_queue.findUnique(args as any);
    }

    return socialContentQueue.findFirst({
      where: args.where,
      include: args.include,
    });
  },

  async count(args?: { where?: Record<string, unknown> }) {
    if (!isConvex()) {
      return prisma.social_content_queue.count(args as any);
    }

    const items = await socialContentQueue.findMany({
      where: args?.where,
      take: 10000,
    });
    return (items as unknown[]).length;
  },

  async create(args: { data: Record<string, unknown> }) {
    if (!isConvex()) {
      return prisma.social_content_queue.create(args as any);
    }

    const d = args.data;
    const convexId = await convexMutation<string>(
      "social/mutations:createPost",
      {
        socialAccountId: d.socialAccountId as string,
        platform: d.platform as string,
        content: d.content as string,
        ...(d.hashtags ? { hashtags: d.hashtags as string[] } : {}),
        ...(d.mediaUrls ? { mediaUrls: d.mediaUrls as string[] } : {}),
      },
    );

    const now = new Date();
    return {
      id: (d.id as string) || convexId || "",
      socialAccountId: d.socialAccountId,
      blogPostId: d.blogPostId ?? null,
      platform: d.platform,
      content: d.content,
      hashtags: d.hashtags ?? [],
      mediaUrls: d.mediaUrls ?? [],
      status: d.status ?? "DRAFT",
      scheduledAt: d.scheduledAt ?? null,
      publishedAt: d.publishedAt ?? null,
      platformPostId: d.platformPostId ?? null,
      platformUrl: d.platformUrl ?? null,
      retryCount: d.retryCount ?? 0,
      errorMessage: d.errorMessage ?? null,
      calendarColor: d.calendarColor ?? null,
      campaignTag: d.campaignTag ?? null,
      createdAt: now,
      updatedAt: now,
    };
  },

  async update(args: { where: { id: string }; data: Record<string, unknown> }) {
    if (!isConvex()) {
      return prisma.social_content_queue.update(args as any);
    }

    const d = args.data;

    // Handle status updates via dedicated mutation
    if (d.status !== undefined) {
      await convexMutation("social/mutations:updatePostStatus", {
        id: args.where.id as any,
        status: d.status as string,
        ...(d.platformPostId !== undefined
          ? { platformPostId: d.platformPostId as string }
          : {}),
        ...(d.platformUrl !== undefined
          ? { platformUrl: d.platformUrl as string }
          : {}),
        ...(d.errorMessage !== undefined
          ? { errorMessage: d.errorMessage as string }
          : {}),
      });
    }

    // Handle scheduling via dedicated mutation
    if (d.scheduledAt !== undefined && d.status === undefined) {
      const scheduledMs =
        d.scheduledAt instanceof Date
          ? d.scheduledAt.getTime()
          : typeof d.scheduledAt === "string"
            ? new Date(d.scheduledAt).getTime()
            : (d.scheduledAt as number);

      await convexMutation("social/mutations:schedulePost", {
        id: args.where.id as any,
        scheduledAt: scheduledMs,
      });
    }

    const existing = await socialContentQueue.findFirst({
      where: { id: args.where.id },
    });
    return existing ? { ...(existing as Record<string, unknown>), ...d } : null;
  },

  async updateMany(args: {
    where: Record<string, unknown>;
    data: Record<string, unknown>;
  }): Promise<BatchResult> {
    if (!isConvex()) {
      return prisma.social_content_queue.updateMany(args as any);
    }

    // Fetch matching items, update individually
    const items = await socialContentQueue.findMany({
      where: args.where,
      take: 10000,
    });

    let updatedCount = 0;
    for (const item of items as Array<Record<string, unknown>>) {
      try {
        await socialContentQueue.update({
          where: { id: item.id as string },
          data: args.data,
        });
        updatedCount++;
      } catch {
        // Continue on individual failures
      }
    }

    return { count: updatedCount };
  },

  async delete(args: { where: { id: string } }) {
    if (!isConvex()) {
      return prisma.social_content_queue.delete(args as any);
    }

    // No dedicated Convex delete mutation for content queue; fall back to Prisma
    return prisma.social_content_queue.delete(args as any);
  },

  async deleteMany(args: {
    where: Record<string, unknown>;
  }): Promise<BatchResult> {
    if (!isConvex()) {
      return prisma.social_content_queue.deleteMany(args as any);
    }

    return prisma.social_content_queue.deleteMany(args as any);
  },
};

// =============================================================================
// Social Analytics
// =============================================================================

const socialAnalytics = {
  async findMany(args: {
    where?: Record<string, unknown>;
    orderBy?: Record<string, string> | Record<string, string>[];
    take?: number;
    skip?: number;
  }) {
    if (!isConvex()) {
      return prisma.social_analytics.findMany(args as any);
    }

    const where = (args.where || {}) as Record<string, unknown>;
    const queueItemId = where.queueItemId as string | undefined;

    if (!queueItemId) return [];

    const doc = await convexQuery<ConvexDoc | null>(
      "social/queries:getAnalytics",
      { queueItemId },
    );

    if (!doc) return [];

    return convexToPrismaShapeMany([doc], ANALYTICS_TS_FIELDS);
  },

  async findFirst(args: { where?: Record<string, unknown> }) {
    if (!isConvex()) {
      return prisma.social_analytics.findFirst(args as any);
    }

    const where = (args.where || {}) as Record<string, unknown>;
    const queueItemId = where.queueItemId as string | undefined;

    if (!queueItemId) return null;

    const doc = await convexQuery<ConvexDoc | null>(
      "social/queries:getAnalytics",
      { queueItemId },
    );

    return doc ? convexToPrismaShape(doc, ANALYTICS_TS_FIELDS) : null;
  },

  async findUnique(args: { where: { id: string } | Record<string, unknown> }) {
    if (!isConvex()) {
      return prisma.social_analytics.findUnique(args as any);
    }

    return socialAnalytics.findFirst({ where: args.where });
  },

  async count(args?: { where?: Record<string, unknown> }) {
    if (!isConvex()) {
      return prisma.social_analytics.count(args as any);
    }

    const items = await socialAnalytics.findMany({
      where: args?.where,
    });
    return (items as unknown[]).length;
  },

  async create(args: { data: Record<string, unknown> }) {
    if (!isConvex()) {
      return prisma.social_analytics.create(args as any);
    }

    // No dedicated Convex create mutation for analytics; fall back to Prisma
    return prisma.social_analytics.create(args as any);
  },

  async update(args: { where: { id: string }; data: Record<string, unknown> }) {
    if (!isConvex()) {
      return prisma.social_analytics.update(args as any);
    }

    return prisma.social_analytics.update(args as any);
  },

  async upsert(args: {
    where: Record<string, unknown>;
    create: Record<string, unknown>;
    update: Record<string, unknown>;
  }) {
    if (!isConvex()) {
      return prisma.social_analytics.upsert(args as any);
    }

    return prisma.social_analytics.upsert(args as any);
  },
};

// =============================================================================
// Social Messages
// =============================================================================

const socialMessages = {
  async findMany(args: {
    where?: Record<string, unknown>;
    orderBy?: Record<string, string> | Record<string, string>[];
    take?: number;
    skip?: number;
  }) {
    if (!isConvex()) {
      return prisma.social_messages.findMany(args as any);
    }

    const where = (args.where || {}) as Record<string, unknown>;
    const socialAccountId = where.socialAccountId as string | undefined;
    const conversationId = where.conversationId as string | undefined;
    const isRead = where.isRead as boolean | undefined;
    const limit = (args.take || 50) + (args.skip || 0);

    // Handle { socialAccountId: { in: [...] } }
    const accountIdFilter = where.socialAccountId;
    if (
      accountIdFilter &&
      typeof accountIdFilter === "object" &&
      "in" in (accountIdFilter as object)
    ) {
      const inIds = (accountIdFilter as { in: string[] }).in;
      let allDocs: ConvexDoc[] = [];
      for (const acctId of inIds) {
        const docs =
          (await convexQuery<ConvexDoc[]>("social/queries:getMessages", {
            socialAccountId: acctId,
            ...(conversationId ? { conversationId } : {}),
            ...(isRead !== undefined ? { isRead } : {}),
            limit,
          })) || [];
        allDocs = allDocs.concat(docs);
      }

      const paginated = applyPagination(allDocs, args.skip, args.take);
      return convexToPrismaShapeMany(paginated, MESSAGE_TS_FIELDS);
    }

    if (!socialAccountId) return [];

    const docs =
      (await convexQuery<ConvexDoc[]>("social/queries:getMessages", {
        socialAccountId,
        ...(conversationId ? { conversationId } : {}),
        ...(isRead !== undefined ? { isRead } : {}),
        limit,
      })) || [];

    // Apply additional where filters
    let filtered = docs;
    if (where.direction) {
      filtered = filtered.filter((d) => d.direction === where.direction);
    }
    if (where.platform) {
      filtered = filtered.filter((d) => d.platform === where.platform);
    }

    const paginated = applyPagination(filtered, args.skip, args.take);
    return convexToPrismaShapeMany(paginated, MESSAGE_TS_FIELDS);
  },

  async findFirst(args: { where?: Record<string, unknown> }) {
    if (!isConvex()) {
      return prisma.social_messages.findFirst(args as any);
    }

    const items = await socialMessages.findMany({
      where: args.where,
      take: 1,
    });
    return (items as unknown[])[0] || null;
  },

  async findUnique(args: { where: { id: string } | Record<string, unknown> }) {
    if (!isConvex()) {
      return prisma.social_messages.findUnique(args as any);
    }

    return socialMessages.findFirst({ where: args.where });
  },

  async count(args?: { where?: Record<string, unknown> }) {
    if (!isConvex()) {
      return prisma.social_messages.count(args as any);
    }

    const items = await socialMessages.findMany({
      where: args?.where,
      take: 10000,
    });
    return (items as unknown[]).length;
  },

  async create(args: { data: Record<string, unknown> }) {
    if (!isConvex()) {
      return prisma.social_messages.create(args as any);
    }

    // No dedicated Convex create mutation for messages; fall back to Prisma
    return prisma.social_messages.create(args as any);
  },

  async update(args: { where: { id: string }; data: Record<string, unknown> }) {
    if (!isConvex()) {
      return prisma.social_messages.update(args as any);
    }

    const d = args.data;

    // Handle markRead via dedicated mutation
    if (d.isRead === true) {
      await convexMutation("social/mutations:markMessageRead", {
        id: args.where.id as any,
      });
    }

    const existing = await socialMessages.findFirst({
      where: { id: args.where.id },
    });
    return existing ? { ...(existing as Record<string, unknown>), ...d } : null;
  },

  async updateMany(args: {
    where: Record<string, unknown>;
    data: Record<string, unknown>;
  }): Promise<BatchResult> {
    if (!isConvex()) {
      return prisma.social_messages.updateMany(args as any);
    }

    const items = await socialMessages.findMany({
      where: args.where,
      take: 10000,
    });

    let updatedCount = 0;
    for (const item of items as Array<Record<string, unknown>>) {
      try {
        if (args.data.isRead === true) {
          await convexMutation("social/mutations:markMessageRead", {
            id: item.id as string as any,
          });
        }
        updatedCount++;
      } catch {
        // Continue on individual failures
      }
    }

    return { count: updatedCount };
  },

  async delete(args: { where: { id: string } }) {
    if (!isConvex()) {
      return prisma.social_messages.delete(args as any);
    }

    return prisma.social_messages.delete(args as any);
  },

  async deleteMany(args: {
    where: Record<string, unknown>;
  }): Promise<BatchResult> {
    if (!isConvex()) {
      return prisma.social_messages.deleteMany(args as any);
    }

    return prisma.social_messages.deleteMany(args as any);
  },
};

// =============================================================================
// Social Trends
// =============================================================================

const socialTrends = {
  async findMany(args: {
    where?: Record<string, unknown>;
    orderBy?: Record<string, string> | Record<string, string>[];
    take?: number;
    skip?: number;
  }) {
    if (!isConvex()) {
      return prisma.social_trends.findMany(args as any);
    }

    const where = (args.where || {}) as Record<string, unknown>;
    const userId = where.userId as string | undefined;

    if (!userId) return [];

    const trendType = where.trendType as string | undefined;
    const platform = where.platform as string | undefined;

    const docs =
      (await convexQuery<ConvexDoc[]>("social/queries:getTrends", {
        userId,
        ...(trendType ? { trendType } : {}),
        ...(platform ? { platform } : {}),
      })) || [];

    // Apply additional filters
    let filtered = docs;

    // Handle expiresAt: { gt: Date } (filter out expired)
    if (where.expiresAt && typeof where.expiresAt === "object") {
      const expiresFilter = where.expiresAt as {
        gt?: Date;
        lt?: Date;
        lte?: Date;
      };
      if (expiresFilter.gt) {
        const gtMs = expiresFilter.gt.getTime();
        filtered = filtered.filter((d) => (d.expiresAt as number) > gtMs);
      }
      if (expiresFilter.lte) {
        const lteMs = expiresFilter.lte.getTime();
        filtered = filtered.filter((d) => (d.expiresAt as number) <= lteMs);
      }
    }

    const paginated = applyPagination(filtered, args.skip, args.take);
    return convexToPrismaShapeMany(paginated, TREND_TS_FIELDS);
  },

  async findFirst(args: { where?: Record<string, unknown> }) {
    if (!isConvex()) {
      return prisma.social_trends.findFirst(args as any);
    }

    const items = await socialTrends.findMany({
      where: args.where,
      take: 1,
    });
    return (items as unknown[])[0] || null;
  },

  async count(args?: { where?: Record<string, unknown> }) {
    if (!isConvex()) {
      return prisma.social_trends.count(args as any);
    }

    const items = await socialTrends.findMany({
      where: args?.where,
      take: 10000,
    });
    return (items as unknown[]).length;
  },

  async create(args: { data: Record<string, unknown> }) {
    if (!isConvex()) {
      return prisma.social_trends.create(args as any);
    }

    // No dedicated Convex create mutation for trends; fall back to Prisma
    return prisma.social_trends.create(args as any);
  },

  async deleteMany(args: {
    where: Record<string, unknown>;
  }): Promise<BatchResult> {
    if (!isConvex()) {
      return prisma.social_trends.deleteMany(args as any);
    }

    // No dedicated Convex delete for trends; fall back to Prisma
    return prisma.social_trends.deleteMany(args as any);
  },
};

// =============================================================================
// Social Posts (standalone, used by API routes)
// =============================================================================

const socialPosts = {
  async findMany(args: {
    where?: Record<string, unknown>;
    orderBy?: Record<string, string> | Record<string, string>[];
    take?: number;
    skip?: number;
  }) {
    if (!isConvex()) {
      return prisma.social_posts.findMany(args as any);
    }

    // No dedicated Convex query for social_posts; fall back to Prisma
    return prisma.social_posts.findMany(args as any);
  },

  async findFirst(args: { where?: Record<string, unknown> }) {
    if (!isConvex()) {
      return prisma.social_posts.findFirst(args as any);
    }

    return prisma.social_posts.findFirst(args as any);
  },

  async findUnique(args: { where: { id: string } }) {
    if (!isConvex()) {
      return prisma.social_posts.findUnique(args as any);
    }

    return prisma.social_posts.findUnique(args as any);
  },

  async count(args?: { where?: Record<string, unknown> }) {
    if (!isConvex()) {
      return prisma.social_posts.count(args as any);
    }

    return prisma.social_posts.count(args as any);
  },

  async create(args: { data: Record<string, unknown> }) {
    if (!isConvex()) {
      return prisma.social_posts.create(args as any);
    }

    return prisma.social_posts.create(args as any);
  },

  async update(args: { where: { id: string }; data: Record<string, unknown> }) {
    if (!isConvex()) {
      return prisma.social_posts.update(args as any);
    }

    return prisma.social_posts.update(args as any);
  },

  async delete(args: { where: { id: string } }) {
    if (!isConvex()) {
      return prisma.social_posts.delete(args as any);
    }

    return prisma.social_posts.delete(args as any);
  },

  async deleteMany(args: {
    where: Record<string, unknown>;
  }): Promise<BatchResult> {
    if (!isConvex()) {
      return prisma.social_posts.deleteMany(args as any);
    }

    return prisma.social_posts.deleteMany(args as any);
  },
};

// =============================================================================
// AI Content Generations
// =============================================================================

const aiContentGenerations = {
  async findMany(args: {
    where?: Record<string, unknown>;
    orderBy?: Record<string, string> | Record<string, string>[];
    take?: number;
    skip?: number;
  }) {
    if (!isConvex()) {
      return prisma.ai_content_generations.findMany(args as any);
    }

    // No dedicated Convex query for ai_content_generations; fall back to Prisma
    return prisma.ai_content_generations.findMany(args as any);
  },

  async findFirst(args: { where?: Record<string, unknown> }) {
    if (!isConvex()) {
      return prisma.ai_content_generations.findFirst(args as any);
    }

    return prisma.ai_content_generations.findFirst(args as any);
  },

  async count(args?: { where?: Record<string, unknown> }) {
    if (!isConvex()) {
      return prisma.ai_content_generations.count(args as any);
    }

    return prisma.ai_content_generations.count(args as any);
  },

  async create(args: { data: Record<string, unknown> }) {
    if (!isConvex()) {
      return prisma.ai_content_generations.create(args as any);
    }

    // No dedicated Convex mutation for AI generations; fall back to Prisma
    return prisma.ai_content_generations.create(args as any);
  },
};

// =============================================================================
// Namespace Exports
// =============================================================================

export const socialAccountsAdapter = socialAccounts;
export const socialContentQueueAdapter = socialContentQueue;
export const socialAnalyticsAdapter = socialAnalytics;
export const socialMessagesAdapter = socialMessages;
export const socialTrendsAdapter = socialTrends;
export const socialPostsAdapter = socialPosts;
export const aiContentGenerationsAdapter = aiContentGenerations;
