import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { AdminAnalyticsFacade } from './admin-analytics.facade';
import { AdminOrdersGateway } from '../../orders/services/admin-orders-gateway.interface';
import { ADMIN_ORDERS_GATEWAY } from '../../orders/services/admin-orders-gateway.token';
import { AdminProductsGateway } from '../../products/services/admin-products-gateway.interface';
import { ADMIN_PRODUCTS_GATEWAY } from '../../products/services/admin-products-gateway.token';
import { ADMIN_CATEGORIES_GATEWAY } from '../../categories/services/admin-categories-gateway.token';
import { AdminModerationGateway } from '../../moderation/services/admin-moderation-gateway.interface';
import { ADMIN_MODERATION_GATEWAY } from '../../moderation/services/admin-moderation-gateway.token';
import { AdminDashboardFacade } from '../../dashboard/facade/admin-dashboard.facade';
import { AdminOrder } from '../../orders/models/admin-order.model';

function makeOrder(overrides: Partial<AdminOrder> = {}): AdminOrder {
  return {
    id: 'order-1',
    createdAt: new Date().toISOString(),
    status: 'completed',
    total: 100,
    currency: 'RUB',
    customer: { email: 'buyer@example.com' },
    items: [{ productId: 'p1', name: 'Widget', quantity: 1, price: 100 }],
    ...overrides,
  } as unknown as AdminOrder;
}

describe('AdminAnalyticsFacade (never-fabricate-a-number contract)', () => {
  let facade: AdminAnalyticsFacade;
  let ordersGateway: jasmine.SpyObj<AdminOrdersGateway>;
  let productsGateway: jasmine.SpyObj<AdminProductsGateway>;
  let categoriesGateway: jasmine.SpyObj<{ loadCategories: () => unknown }>;
  let moderationGateway: jasmine.SpyObj<AdminModerationGateway>;
  let dashboardFacade: jasmine.SpyObj<AdminDashboardFacade>;

  function configure(bootstrapPresent: boolean): void {
    ordersGateway = jasmine.createSpyObj('ADMIN_ORDERS_GATEWAY', ['loadOrders']);
    productsGateway = jasmine.createSpyObj('ADMIN_PRODUCTS_GATEWAY', ['loadProducts']);
    categoriesGateway = jasmine.createSpyObj('ADMIN_CATEGORIES_GATEWAY', ['loadCategories']);
    moderationGateway = jasmine.createSpyObj('ADMIN_MODERATION_GATEWAY', ['loadReviews']);
    dashboardFacade = jasmine.createSpyObj('AdminDashboardFacade', [
      'ensureLoaded', 'activityEntries', 'bootstrap', 'validationIssues', 'enabledWidgetsCount', 'staticPagesUnpublishedCount',
    ]);

    ordersGateway.loadOrders.and.returnValue(of({ items: [makeOrder()], total: 1 } as any));
    productsGateway.loadProducts.and.returnValue(of({ items: [], total: 0 } as any));
    categoriesGateway.loadCategories.and.returnValue(of([]));
    moderationGateway.loadReviews.and.returnValue(of({ items: [], total: 0 } as any));
    dashboardFacade.activityEntries.and.returnValue([]);
    dashboardFacade.bootstrap.and.returnValue(bootstrapPresent ? ({ schemaVersion: '1', tenant: { id: 't1' } } as any) : null);
    dashboardFacade.validationIssues.and.returnValue([]);
    dashboardFacade.enabledWidgetsCount.and.returnValue(0);
    dashboardFacade.staticPagesUnpublishedCount.and.returnValue(0);

    TestBed.configureTestingModule({
      providers: [
        { provide: ADMIN_ORDERS_GATEWAY, useValue: ordersGateway },
        { provide: ADMIN_PRODUCTS_GATEWAY, useValue: productsGateway },
        { provide: ADMIN_CATEGORIES_GATEWAY, useValue: categoriesGateway },
        { provide: ADMIN_MODERATION_GATEWAY, useValue: moderationGateway },
        { provide: AdminDashboardFacade, useValue: dashboardFacade },
      ],
    });

    facade = TestBed.inject(AdminAnalyticsFacade);
  }

  it('never fabricates conversionRate - stays null even with real order data', () => {
    configure(true);
    facade.load();

    expect(facade.summary()?.conversionRate).toBeNull();
    expect(facade.summary()?.revenueTotal).toBe(100);
    expect(facade.summary()?.ordersCount).toBe(1);
  });

  it('never fabricates the "performance" health check - always unknown (no real data source)', () => {
    configure(true);
    facade.load();

    const performance = facade.marketplaceHealth().find(check => check.code === 'performance');
    expect(performance?.status).toBe('unknown');
  });

  it('reports backend-connectivity and homepage-configured as unknown when bootstrap has not loaded, instead of guessing', () => {
    configure(false);
    facade.load();

    const backend = facade.marketplaceHealth().find(check => check.code === 'backend-connectivity');
    const homepage = facade.marketplaceHealth().find(check => check.code === 'homepage-configured');
    expect(backend?.status).toBe('unknown');
    expect(homepage?.status).toBe('unknown');
  });

  it('reports backend-connectivity as healthy only once bootstrap is actually present', () => {
    configure(true);
    facade.load();

    const backend = facade.marketplaceHealth().find(check => check.code === 'backend-connectivity');
    expect(backend?.status).toBe('healthy');
  });
});
