jest.mock('../../../queue', () => ({
  translationQueue: {
    add: jest.fn().mockResolvedValue({ id: 'mock-job-id' }),
    process: jest.fn(),
    on: jest.fn(),
    close: jest.fn().mockResolvedValue(undefined),
  },
}));

import request from 'supertest';
import { Application } from 'express';
import { createServer } from '../../../server';
import { prismaMock } from '../../setup';

const STATUS_PATH = '/v1/international/license/status';
const LICENSE_KEY = 'INTL-AAAA-BBBB-CCCC';
const SITE_URL = 'https://client.example.com';

function licenseRow(overrides: Record<string, unknown> = {}) {
  return {
    id: '11111111-1111-1111-1111-111111111111',
    key: LICENSE_KEY,
    plugin: 'international',
    plan_tier: 'professional',
    status: 'active',
    sites_allowed: 5,
    languages_allowed: 5,
    expires_at: new Date(Date.now() + 30 * 24 * 3600 * 1000),
    activations: [{ site_url: SITE_URL }],
    ...overrides,
  } as any;
}

describe('POST international license status', () => {
  let app: Application;

  beforeAll(() => {
    app = createServer();
  });

  it('validates credentials from the JSON body', async () => {
    prismaMock.license.findUnique.mockResolvedValue(licenseRow());

    const response = await request(app).post(STATUS_PATH).send({
      license_key: LICENSE_KEY,
      site_url: SITE_URL,
      product: 'international-press-zone',
    });

    expect(response.status).toBe(200);
    expect(response.body.success).toBe(true);
    expect(response.body.data.status).toBe('active');
    expect(prismaMock.license.findUnique).toHaveBeenCalledWith(
      expect.objectContaining({
        where: { key_hash: expect.stringMatching(/^[a-f0-9]{64}$/) },
      })
    );
  });

  it('rejects missing JSON credentials', async () => {
    const response = await request(app).post(STATUS_PATH).send({});

    expect(response.status).toBe(400);
    expect(prismaMock.license.findUnique).not.toHaveBeenCalled();
  });

  it('maps an unknown license to the licensing error contract', async () => {
    prismaMock.license.findUnique.mockResolvedValue(null);

    const response = await request(app).post(STATUS_PATH).send({
      license_key: LICENSE_KEY,
      site_url: SITE_URL,
    });

    expect(response.status).toBe(404);
    expect(response.body.error.code).toBe('INVALID_LICENSE');
  });
});
