import { and, desc, eq } from 'drizzle-orm';
import { getVesting, type VestingSchema } from '@platform-modules/ledger/vesting';
import type { Querier } from '@platform-modules/db';
import { formatAgorotShekels } from '@/lib/money.js';
import {
  affiliateEnrollments,
  affiliateEntriesTable,
  ledgerEntries,
  ledgerEntryVesting,
  referrals,
} from '@/server/db/schema';
import { minorForApi } from '@/server/referrals/ledger.js';
import type { KnowledgeAdapter, KnowledgeChunk } from './types';
import type { AdapterContext } from '@/server/support/types';

const LABEL = 'היסטוריית שותפים';

export const affiliateHistoryAdapter: KnowledgeAdapter = {
  id: 'affiliate-history',
  label: LABEL,
  description: 'הפניות ועמלות שותפים של המשתמש',
  async fetch(ctx: AdapterContext): Promise<KnowledgeChunk> {
    const base: KnowledgeChunk = {
      adapterId: 'affiliate-history',
      label: LABEL,
      data: {},
      summary: '',
    };

    try {
      const referralRows = await ctx.db
        .select({
          id: referrals.id,
          status: referrals.status,
          kind: referrals.kind,
          commissionPct: referrals.commissionPct,
          createdAt: referrals.createdAt,
        })
        .from(referrals)
        .where(eq(referrals.referrerUserId, ctx.userId))
        .orderBy(desc(referrals.createdAt))
        .limit(20);

      const affiliateReferrals = referralRows.filter((r) => r.kind === 'affiliate');

      const commissionRows = await ctx.db
        .select({
          amountAgorot: ledgerEntries.delta,
          createdAt: ledgerEntries.createdAt,
          matureAt: ledgerEntryVesting.matureAt,
        })
        .from(affiliateEntriesTable)
        .innerJoin(ledgerEntries, eq(ledgerEntries.id, affiliateEntriesTable.entryId))
        .leftJoin(ledgerEntryVesting, eq(ledgerEntryVesting.entryId, affiliateEntriesTable.entryId))
        .where(
          and(
            eq(affiliateEntriesTable.ownerId, ctx.userId),
            eq(affiliateEntriesTable.entryType, 'affiliate_commission'),
          ),
        )
        .orderBy(desc(ledgerEntries.createdAt))
        .limit(10);

      const [enrollment] = await ctx.db
        .select({
          status: affiliateEnrollments.status,
          commissionPct: affiliateEnrollments.commissionPct,
        })
        .from(affiliateEnrollments)
        .where(eq(affiliateEnrollments.userId, ctx.userId))
        .limit(1);

      const vesting = await getVesting(ctx.db as unknown as Querier<VestingSchema>, ctx.userId);
      const pendingAgorot = minorForApi(vesting.pendingMinor);
      const withdrawableAgorot = minorForApi(vesting.withdrawableMinor);
      const tier = enrollment?.commissionPct ?? null;

      const summary =
        affiliateReferrals.length === 0
          ? 'אין היסטוריית שותפים'
          : `${affiliateReferrals.length} הפניות שותפים, עמלה ממתינה ${formatAgorotShekels(pendingAgorot)}` +
            (tier !== null ? `, שיעור ${tier}%` : '');

      return {
        ...base,
        data: {
          referralCount: affiliateReferrals.length,
          referrals: affiliateReferrals,
          commissions: commissionRows,
          pendingAgorot,
          withdrawableAgorot,
          enrollmentStatus: enrollment?.status ?? null,
          commissionPct: tier,
        },
        summary,
      };
    } catch (err) {
      return { ...base, error: String(err) };
    }
  },
};
