import { test, expectFixture as expect } from '../helpers/test-fixtures';

test.describe('Tenant admin add-on upgrades', () => {
  test.beforeEach(async ({ tenantAdminCredentials, signInTenantAdmin }) => {
    test.skip(!tenantAdminCredentials, 'Provide E2E_TENANT_EMAIL and E2E_TENANT_PASSWORD to run admin tests.');
    await signInTenantAdmin();
  });

  test('purchasing an add-on increases photo limits in moderation view', async ({ page }) => {
    let addonPurchased = false;

    const initialLimits = {
      photos: {
        limit: 120,
        used: 120,
        remaining: 0,
        percentage: 100,
        state: 'limit_reached',
        threshold_reached: 120,
        next_threshold: null,
        thresholds: [80, 95, 120],
      },
      guests: null,
      gallery: {
        state: 'warning',
        expires_at: new Date(Date.now() + 86400000).toISOString(),
        days_remaining: 1,
        warning_thresholds: [7, 1],
        warning_triggered: 1,
        warning_sent_at: null,
        expired_notified_at: null,
      },
      can_upload_photos: false,
      can_add_guests: true,
    };

    const upgradedLimits = {
      photos: {
        limit: 620,
        used: 120,
        remaining: 500,
        percentage: 19,
        state: 'ok',
        threshold_reached: 80,
        next_threshold: 95,
        thresholds: [80, 95, 120, 600],
      },
      guests: null,
      gallery: initialLimits.gallery,
      can_upload_photos: true,
      can_add_guests: true,
    };

    await page.route('**/api/v1/tenant/addons/catalog', async (route) => {
      await route.fulfill({
        status: 200,
        contentType: 'application/json',
        body: JSON.stringify({
          data: [
            { key: 'extra_photos_500', label: '+500 Fotos', price_id: 'pri_addon_photos', increments: { extra_photos: 500 } },
          ],
        }),
      });
    });

    await page.route('**/api/v1/tenant/events/limit-event/photos', async (route) => {
      await route.fulfill({
        status: 200,
        contentType: 'application/json',
        body: JSON.stringify({
          data: [],
          limits: addonPurchased ? upgradedLimits : initialLimits,
        }),
      });
    });

    await page.route('**/api/v1/tenant/events/limit-event', async (route) => {
      const timestamp = new Date().toISOString();

      await route.fulfill({
        status: 200,
        contentType: 'application/json',
        body: JSON.stringify({
          data: {
            id: 101,
            name: 'Limit Event',
            slug: 'limit-event',
            event_date: timestamp.slice(0, 10),
            event_type_id: null,
            event_type: null,
            status: 'published',
            addons: addonPurchased
              ? [
                  {
                    id: 1,
                    key: 'extra_photos_500',
                    addon_key: 'extra_photos_500',
                    label: '+500 Fotos',
                    status: 'completed',
                    price_id: 'pri_addon_photos',
                    transaction_id: 'txn_addon_1',
                    extra_photos: 500,
                    extra_guests: 0,
                    extra_gallery_days: 0,
                    purchased_at: timestamp,
                    metadata: { price_eur: 49 },
                  },
                ]
              : [],
          },
        }),
      });
    });

    await page.route('**/api/v1/tenant/events/limit-event/addons/checkout', async (route) => {
      addonPurchased = true;

      await route.fulfill({
        status: 200,
        contentType: 'application/json',
        body: JSON.stringify({
          checkout_url: '/event-admin/mobile/events/limit-event/control-room?addon_success=1',
          checkout_id: 'chk_addon_1',
          expires_at: new Date(Date.now() + 600000).toISOString(),
        }),
      });
    });

    await page.goto('/event-admin/mobile/events/limit-event/control-room');

    await expect(page.getByText(/Upload-Limit erreicht/i)).toBeVisible();

    const purchaseButton = page.getByRole('button', { name: /Mehr Fotos freischalten/i });
    await expect(purchaseButton).toBeVisible();
    await purchaseButton.click();

    await expect(page).toHaveURL(/addon_success=1/);

    await expect(page.getByText(/Upload-Limit erreicht/i)).not.toBeVisible({ timeout: 10000 });
    await expect(page.getByText(/\+500\s*Fotos/i)).toBeVisible();
  });
});
