import { beforeEach, describe, expect, it, vi } from 'vitest';

const nextServer = vi.hoisted(() => {
  const next = vi.fn((init?: { request?: { headers?: Headers } }) => ({
    kind: 'next',
    init,
    cookies: {
      set: vi.fn(),
    },
    headers: new Headers(),
  }));
  const redirect = vi.fn((url: URL) => ({
    kind: 'redirect',
    url: url.toString(),
    cookies: {
      set: vi.fn(),
    },
    headers: new Headers(),
  }));
  return { next, redirect };
});

vi.mock('next/server', () => ({
  NextResponse: {
    next: nextServer.next,
    redirect: nextServer.redirect,
  },
}));

function cloneableUrl(input: string): URL {
  const url = new URL(input);
  (url as URL & { clone: () => URL }).clone = () => cloneableUrl(url.toString());
  return url;
}

function request(input: string) {
  return {
    nextUrl: cloneableUrl(input),
    cookies: {
      get: vi.fn(),
    },
    headers: new Headers(),
  };
}

type ProxyTestResponse = {
  kind: 'next' | 'redirect';
  url?: string;
};

function runProxy(proxy: (request: never) => unknown, input: ReturnType<typeof request>) {
  return proxy(input as never) as ProxyTestResponse;
}

beforeEach(() => {
  nextServer.next.mockClear();
  nextServer.redirect.mockClear();
});

describe('homepage proxy app boundaries', () => {
  it('does not localize Carplace proxy paths', async () => {
    const { proxy } = await import('@/proxy');

    const response = runProxy(proxy, request('https://rentaldrivego.ma/carplace/en'));

    expect(response.kind).toBe('next');
    expect(nextServer.redirect).not.toHaveBeenCalled();
  });

  it('redirects the root path to locale and mode segments', async () => {
    const { proxy } = await import('@/proxy');

    const input = request('https://rentaldrivego.ma/');
    input.headers.set('accept-language', 'fr;q=1,en;q=0.8');
    const response = runProxy(proxy, input);

    expect(response).toMatchObject({
      kind: 'redirect',
      url: 'https://rentaldrivego.ma/fr/system',
    });
  });

  it('redirects legacy localized slugs to mode-aware localized slugs', async () => {
    const { proxy } = await import('@/proxy');

    const response = runProxy(proxy, request('https://rentaldrivego.ma/en/privacy'));

    expect(response).toMatchObject({
      kind: 'redirect',
      url: 'https://rentaldrivego.ma/en/system/privacy',
    });
  });

});
