/**
 * Cumas365 CRM Adapter — example reference implementation.
 *
 * Wraps the existing `src/lib/crm/cumas-client.ts` low-level client into the
 * generic `CrmAdapter` interface. The low-level client stays in `lib/` because
 * it has many Cumas-specific helpers used by API routes today; this thin
 * wrapper exposes only what Mailforge's core needs.
 *
 * To use this adapter, set in `adapters.config.ts`:
 *   import { cumasAdapter } from "@/adapters/crm/cumas";
 *   export const adapters = { crm: cumasAdapter, ... };
 *
 * Env vars required:
 *   CRM_BASE_URL, CRM_USERNAME, CRM_PASSWORD
 *
 * NOTE: Cumas has three resources (business / evb / orders). This adapter
 * defaults to BUSINESS. Override via `customFilters.resource` on listContacts.
 */

import type { CrmAdapter } from './interface';
import type { UserContext } from '@/core/types';
import type { Contact, ContactFilter, ConversionEvent } from '@/adapters/types';
import {
  buildBusinessAudience,
  buildOrderAudience,
  buildEvbAudience,
  isCumasConfigured,
  type AudienceRecipient,
} from '@/lib/crm/cumas-client';
import { buildLoginLink } from './cumas-login-link';

type CumasResource = 'business' | 'orders' | 'evb';

function audienceToContact(rec: AudienceRecipient): Contact {
  return {
    externalId: rec.cumasId ? String(rec.cumasId) : rec.email,
    email: rec.email,
    firstName: rec.firstName,
    lastName: rec.lastName,
    company: rec.company,
    customData: {
      source: rec.source,
      fullName: rec.fullName ?? null,
    },
  };
}

export const cumasAdapter: CrmAdapter = {
  name: 'cumas',

  isConfigured() {
    return isCumasConfigured();
  },

  async listContacts(filter: ContactFilter, _ctx: UserContext): Promise<Contact[]> {
    const resource: CumasResource =
      (filter.customFilters?.resource as CumasResource | undefined) ?? 'business';

    // maxRecords mirrors limit×offset budget so we don't scan unnecessarily.
    const maxRecords =
      typeof filter.customFilters?.maxRecords === 'number'
        ? filter.customFilters.maxRecords
        : ((filter.limit ?? 100) + (filter.offset ?? 0)) || 100;

    let result: { recipients: AudienceRecipient[] };
    switch (resource) {
      case 'orders':
        result = await buildOrderAudience({ maxRecords });
        break;
      case 'evb':
        result = await buildEvbAudience({ maxRecords });
        break;
      case 'business':
      default:
        result = await buildBusinessAudience({ maxRecords });
    }

    const audience = result.recipients;
    const limit = filter.limit ?? audience.length;
    const offset = filter.offset ?? 0;
    return audience.slice(offset, offset + limit).map(audienceToContact);
  },

  async getContactById(_id: string, _ctx: UserContext): Promise<Contact | null> {
    // Cumas-client has no direct getById — for single-record lookups we would
    // need to call the resource list endpoint with id-filter. Left for callers
    // that need it; current Mailforge core does not.
    return null;
  },

  async pollConversions(_since: Date, _ctx: UserContext): Promise<ConversionEvent[]> {
    // Conversion polling has its own dedicated helper in
    // `src/lib/conversions/cumas-poller.ts`. The polling loop calls it directly
    // for now; we'll route through the adapter in Phase B.4.
    return [];
  },

  async listSegments(_ctx: UserContext) {
    // Cumas resources serve as the segment-equivalent.
    return [
      { id: 'business', label: 'Geschäftskunden (its_business_datas)' },
      { id: 'evb', label: 'Versicherungen (evbs)' },
      { id: 'orders', label: 'Privat-Bestellungen (order_private_shops)' },
    ];
  },

  resolveLoginLink({ workspaceShopDomain, recipientExternalId, recipientPoolType, recipientId }) {
    if (!workspaceShopDomain || !recipientExternalId) return '';
    const pool = recipientPoolType === 'business' ? 'business' : 'private';
    return buildLoginLink(workspaceShopDomain, recipientExternalId, pool, recipientId);
  },
};
