import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { MealieClient, MealieIntegration, MealieMapper } from '../../ts/integrations/mealie/index.js';

const readBody = async (requestArg: IncomingMessage): Promise<string> => {
  const chunks: Buffer[] = [];
  for await (const chunk of requestArg) {
    chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
  }
  return Buffer.concat(chunks).toString('utf8');
};

const json = (responseArg: ServerResponse, valueArg: unknown, statusArg = 200): void => {
  responseArg.statusCode = statusArg;
  responseArg.setHeader('content-type', 'application/json');
  responseArg.end(JSON.stringify(valueArg));
};

tap.test('reads Mealie snapshots and services over the local HTTP API', async () => {
  const requests: Array<{ method?: string; url?: string; body?: string; authorization?: string }> = [];
  const server = createServer((requestArg: IncomingMessage, responseArg: ServerResponse) => {
    void (async () => {
      const body = requestArg.method === 'POST' || requestArg.method === 'PUT' ? await readBody(requestArg) : undefined;
      requests.push({ method: requestArg.method, url: requestArg.url, body, authorization: requestArg.headers.authorization });
      const url = new URL(requestArg.url || '/', 'http://127.0.0.1');

      if (requestArg.headers.authorization !== 'Bearer secret') {
        json(responseArg, { detail: 'unauthorized' }, 401);
        return;
      }
      if (url.pathname === '/api/app/about') {
        json(responseArg, { version: 'v3.8.0' });
        return;
      }
      if (url.pathname === '/api/users/self') {
        json(responseArg, { id: 'user-1', username: 'chef', email: 'chef@example.test', fullName: 'Chef User' });
        return;
      }
      if (url.pathname === '/api/households/statistics') {
        json(responseArg, { totalRecipes: 12, totalUsers: 2, totalCategories: 3, totalTags: 4, totalTools: 5 });
        return;
      }
      if (url.pathname === '/api/households/mealplans' && requestArg.method === 'GET') {
        json(responseArg, { items: [{ id: 1, date: '2026-05-11', entryType: 'dinner', title: 'Soup', text: 'Tomato', recipe: null }] });
        return;
      }
      if (url.pathname === '/api/households/shopping/lists') {
        json(responseArg, { items: [{ id: 'list-1', name: 'Groceries' }] });
        return;
      }
      if (url.pathname === '/api/households/shopping/items') {
        expect(url.searchParams.get('queryFilter')).toEqual('shoppingListId=list-1');
        json(responseArg, { items: [{ id: 'item-1', shoppingListId: 'list-1', display: 'Tomatoes', checked: false, position: 0, quantity: 1 }] });
        return;
      }
      if (url.pathname === '/api/recipes') {
        expect(url.searchParams.get('search')).toEqual('soup');
        json(responseArg, { items: [{ id: 'recipe-1', name: 'Tomato soup', slug: 'tomato-soup' }] });
        return;
      }
      if (url.pathname === '/api/recipes/recipe-1') {
        json(responseArg, { id: 'recipe-1', name: 'Tomato soup', recipeIngredient: [], recipeInstructions: [] });
        return;
      }
      if (url.pathname === '/api/households/mealplans/random' && requestArg.method === 'POST') {
        expect(body).toContain('entryType');
        json(responseArg, { id: 2, date: '2026-05-12', entryType: 'dinner', title: 'Random dinner', recipe: null });
        return;
      }
      responseArg.statusCode = 404;
      responseArg.end('{}');
    })().catch((errorArg) => {
      responseArg.statusCode = 500;
      responseArg.end(String(errorArg));
    });
  });

  await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
  try {
    const address = server.address();
    const port = typeof address === 'object' && address ? address.port : 0;
    const url = `http://127.0.0.1:${port}`;
    const client = new MealieClient({ url, token: 'secret', timeoutMs: 1000 });
    const snapshot = await client.getSnapshot(true);
    const entities = MealieMapper.toEntities(snapshot);
    const recipes = await client.execute({ domain: 'mealie', service: 'get_recipes', target: {}, data: { search_terms: 'soup', result_limit: 2 } });
    const random = await client.execute({ domain: 'mealie', service: 'set_random_mealplan', target: {}, data: { date: '2026-05-12', entry_type: 'dinner' } });
    const runtime = await new MealieIntegration().setup({ url, token: 'secret', timeoutMs: 1000 }, {});
    const status = await runtime.callService!({ domain: 'mealie', service: 'status', target: {} });

    expect(snapshot.online).toBeTrue();
    expect(snapshot.source).toEqual('http');
    expect(snapshot.device.model).toEqual('Mealie v3.8.0');
    expect(entities.find((entityArg) => entityArg.attributes?.key === 'recipes')?.state).toEqual(12);
    expect(entities.find((entityArg) => entityArg.attributes?.key === 'shopping_items')?.state).toEqual(1);
    expect(recipes.success).toBeTrue();
    expect(random.success).toBeTrue();
    expect(status.success).toBeTrue();
    expect((status.data as { online?: boolean }).online).toBeTrue();
    expect(requests.some((requestArg) => requestArg.authorization === 'Bearer secret')).toBeTrue();
    expect(requests.some((requestArg) => requestArg.method === 'POST' && requestArg.url === '/api/households/mealplans/random' && requestArg.body?.includes('entryType'))).toBeTrue();
    await runtime.destroy();
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

export default tap.start();
