import { TestBed } from '@angular/core/testing';
import { ActivatedRoute, convertToParamMap, Router } from '@angular/router';

import { CheckoutService, PurchaseDetailResponse } from '../../../../core/services/checkout.service';
import { Tenant } from '../../../../core/services/tenant.interface';
import { TenantService } from '../../../../core/services/tenant.service';
import { PurchaseStatusPageComponent } from './purchase-status-page.component';

const tenant: Tenant = {
  id: 1,
  codigo: 'tickets-tenant',
  nombre: 'Tickets tenant',
  dominio: 'tickets.local',
  primary_color: '#000000',
  secondary_color: '#000000',
  danger_color: '#000000',
  success_color: '#000000',
  header_bg_color: '#000000',
  footer_bg_color: '#000000',
  header_logo: '',
  footer_logo: '',
  categories: [],
  social_media: [
    {
      code: 'whatsapp',
      icon: 'whatsapp',
      name: 'WhatsApp',
      url: 'https://wa.me/543411234567',
    },
  ],
  menues: [
    {
      id: 1,
      code: 'account',
      label: 'Mi cuenta',
      parent_menu_code: null,
      content_type: 'dynamic',
      route: '/mi-cuenta',
      submenues: [
        {
          id: 2,
          code: 'account.tickets',
          label: 'Mis tickets',
          parent_menu_code: 'account',
          content_type: 'dynamic',
          route: '/mi-cuenta/tickets',
          submenues: [],
        },
      ],
    },
  ],
};

const purchase = (hasGeneratedTickets: boolean): PurchaseDetailResponse =>
  ({
    status: 'paid',
    has_generated_tickets: hasGeneratedTickets,
    tickets_count: hasGeneratedTickets ? 1 : 0,
  }) as PurchaseDetailResponse;

describe('PurchaseStatusPageComponent', () => {
  beforeEach(() => {
    TestBed.resetTestingModule();
  });

  async function render(hasGeneratedTickets: boolean) {
    const checkoutService = {
      getPurchase: vi.fn().mockResolvedValue(purchase(hasGeneratedTickets)),
      withCustomLoading() {
        return this;
      },
    };
    const router = {
      navigate: vi.fn().mockResolvedValue(true),
      navigateByUrl: vi.fn().mockResolvedValue(true),
    };

    await TestBed.configureTestingModule({
      imports: [PurchaseStatusPageComponent],
      providers: [
        { provide: CheckoutService, useValue: checkoutService },
        { provide: TenantService, useValue: { tenant: () => tenant } },
        {
          provide: ActivatedRoute,
          useValue: { snapshot: { paramMap: convertToParamMap({ id: '42' }) } },
        },
        { provide: Router, useValue: router },
      ],
    }).compileComponents();

    const fixture = TestBed.createComponent(PurchaseStatusPageComponent);
    fixture.detectChanges();
    await fixture.whenStable();
    fixture.detectChanges();

    return {
      fixture,
      element: fixture.nativeElement as HTMLElement,
      checkoutService,
      router,
    };
  }

  it('shows the tickets action when this purchase generated tickets', async () => {
    const { element, checkoutService, router } = await render(true);

    expect(checkoutService.getPurchase).toHaveBeenCalledOnce();
    expect(element.textContent).toContain('Ver mis tickets');
    expect(element.textContent).not.toContain('WhatsApp');

    element.querySelector<HTMLButtonElement>('app-button button')?.click();

    expect(router.navigateByUrl).toHaveBeenCalledWith('/mi-cuenta/tickets');
  });

  it('shows the tenant WhatsApp action when this purchase did not generate tickets', async () => {
    const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null);
    const { element } = await render(false);

    expect(element.textContent).toContain('WhatsApp');
    expect(element.textContent).not.toContain('Ver mis tickets');

    element.querySelector<HTMLButtonElement>('app-button button')?.click();

    expect(openSpy).toHaveBeenCalledWith(
      'https://wa.me/543411234567',
      '_blank',
      'noopener,noreferrer',
    );

    openSpy.mockRestore();
  });
});
