import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { AdminProductsLocalGateway } from './admin-products-local.gateway';
import { BackofficeDataService } from '../../../../core/backoffice/backoffice-data.service';
import { AdminCategoriesLocalGateway } from '../../categories/services/admin-categories-local.gateway';
import { ProductCardConfig } from '../../../../shared/models/ui';
import { AdminProductListFilters } from '../models/admin-product.model';

function makeProductCard(id: string): ProductCardConfig {
  return {
    id,
    sku: `SKU-${id}`,
    title: `Product ${id}`,
    imageUrl: '/image.png',
    price: { amount: 1000, currency: 'RUB' },
    stockStatus: 'in_stock',
  };
}

function makeFilters(): AdminProductListFilters {
  return {
    search: '',
    categoryId: null,
    visibility: 'all',
    stock: 'all',
    includeArchived: true,
    sort: 'title',
    page: 1,
    pageSize: 50,
  };
}

describe('AdminProductsLocalGateway visits field', () => {
  let gateway: AdminProductsLocalGateway;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        { provide: BackofficeDataService, useValue: { loadProducts: () => of([makeProductCard('p1'), makeProductCard('p2')]) } },
        { provide: AdminCategoriesLocalGateway, useValue: { loadCategories: () => of([{ id: 'cat-001', title: 'Category' }]) } },
      ],
    });
    gateway = TestBed.inject(AdminProductsLocalGateway);
  });

  it('defaults visits to 0 on every loaded product', (done) => {
    gateway.loadProducts(makeFilters()).subscribe(result => {
      expect(result.items.length).toBe(2);
      expect(result.items.every(product => product.visits === 0)).toBe(true);
      done();
    });
  });

  it('resets visits to 0 on a duplicated product', (done) => {
    gateway.loadProducts(makeFilters()).subscribe(result => {
      const source = result.items[0];
      gateway.duplicateProduct(source.id).subscribe(duplicated => {
        expect(duplicated).not.toBeNull();
        expect(duplicated!.visits).toBe(0);
        done();
      });
    });
  });
});
