import { http, HttpResponse } from 'msw';

/**
 * FE-API-019: MSW Mock Handlers
 * Mock request handlers for development and testing
 *
 * Note: Handlers should match the full URL path that the client sends.
 * Since apiClient uses baseURL (e.g., http://127.0.0.1:8080/api/v1),
 * handlers should match paths like '/api/v1/*' or use full URLs.
 */

// Mock handlers pour les tests et le développement
export const handlers = [
  // Auth endpoints
  http.post('*/api/v1/auth/login', async ({ request }) => {
    const body = (await request.json()) as { email: string; password: string };

    if (body.email === 'test@example.com' && body.password === 'password123') {
      return HttpResponse.json({
        access_token: 'mock_access_token_123',
        refresh_token: 'mock_refresh_token_123',
        user: {
          id: 1,
          username: 'testuser',
          email: 'test@example.com',
          created_at: '2024-01-01T00:00:00Z',
        },
      });
    }

    return HttpResponse.json({ error: 'Invalid credentials' }, { status: 401 });
  }),

  http.post('*/api/v1/auth/register', async ({ request }) => {
    const body = (await request.json()) as {
      username: string;
      email: string;
      password: string;
    };

    if (body.email === 'existing@example.com') {
      return HttpResponse.json(
        { error: 'User already exists' },
        { status: 409 },
      );
    }

    return HttpResponse.json(
      {
        access_token: 'mock_access_token_123',
        refresh_token: 'mock_refresh_token_123',
        user: {
          id: 2,
          username: body.username,
          email: body.email,
          created_at: '2024-01-01T00:00:00Z',
        },
      },
      { status: 201 },
    );
  }),

  http.post('*/api/v1/auth/refresh', async ({ request }) => {
    const body = (await request.json()) as { refresh_token: string };

    if (body.refresh_token === 'valid_refresh_token') {
      return HttpResponse.json({
        access_token: 'new_access_token_123',
        refresh_token: 'new_refresh_token_123',
      });
    }

    return HttpResponse.json(
      { error: 'Invalid refresh token' },
      { status: 401 },
    );
  }),

  // User endpoints
  http.get('*/api/v1/auth/me', ({ request }) => {
    const authHeader = request.headers.get('authorization');

    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return HttpResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    return HttpResponse.json({
      id: 1,
      username: 'testuser',
      email: 'test@example.com',
      created_at: '2024-01-01T00:00:00Z',
      updated_at: '2024-01-01T00:00:00Z',
    });
  }),

  http.get('*/api/v1/users/profile', ({ request }) => {
    const authHeader = request.headers.get('authorization');

    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return HttpResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    return HttpResponse.json({
      id: 1,
      username: 'testuser',
      email: 'test@example.com',
      created_at: '2024-01-01T00:00:00Z',
      updated_at: '2024-01-01T00:00:00Z',
    });
  }),

  http.put('*/api/v1/users/profile', async ({ request }) => {
    const authHeader = request.headers.get('authorization');

    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return HttpResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = (await request.json()) as {
      username?: string;
      email?: string;
    };

    return HttpResponse.json({
      id: 1,
      username: body.username || 'testuser',
      email: body.email || 'test@example.com',
      created_at: '2024-01-01T00:00:00Z',
      updated_at: new Date().toISOString(),
    });
  }),

  // Roles endpoints
  http.get('*/api/v1/roles', ({ request }) => {
    const authHeader = request.headers.get('authorization');

    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return HttpResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    return HttpResponse.json([
      {
        id: 1,
        name: 'admin',
        description: 'Administrator role',
        permissions: ['*'],
        created_at: '2024-01-01T00:00:00Z',
      },
      {
        id: 2,
        name: 'user',
        description: 'Regular user role',
        permissions: ['read:own'],
        created_at: '2024-01-01T00:00:00Z',
      },
    ]);
  }),

  http.get('*/api/v1/roles/:id', ({ request, params }) => {
    const authHeader = request.headers.get('authorization');

    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return HttpResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const { id } = params as { id: string };

    return HttpResponse.json({
      id: parseInt(id, 10),
      name: id === '1' ? 'admin' : 'user',
      description: id === '1' ? 'Administrator role' : 'Regular user role',
      permissions: id === '1' ? ['*'] : ['read:own'],
      created_at: '2024-01-01T00:00:00Z',
    });
  }),

  // Conversations endpoints
  http.get('*/api/v1/conversations', ({ request }) => {
    const authHeader = request.headers.get('authorization');

    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return HttpResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    return HttpResponse.json([
      {
        id: 'conv-1',
        name: 'General Chat',
        type: 'group',
        last_message: {
          id: 'msg-1',
          content: 'Hello, world!',
          sender: { id: 1, username: 'user1' },
          timestamp: '2024-01-01T10:00:00Z',
        },
        unread_count: 0,
        created_at: '2024-01-01T00:00:00Z',
      },
      {
        id: 'conv-2',
        name: 'Direct Message',
        type: 'direct',
        last_message: {
          id: 'msg-2',
          content: 'How are you?',
          sender: { id: 2, username: 'user2' },
          timestamp: '2024-01-01T10:01:00Z',
        },
        unread_count: 2,
        created_at: '2024-01-01T00:00:00Z',
      },
    ]);
  }),

  http.get('*/api/v1/conversations/:id/messages', ({ request, params }) => {
    const authHeader = request.headers.get('authorization');

    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return HttpResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const { id: _ } = params as { id: string };

    return HttpResponse.json([
      {
        id: 'msg-1',
        content: 'Hello, world!',
        sender: { id: 1, username: 'user1' },
        timestamp: '2024-01-01T10:00:00Z',
        type: 'text',
      },
      {
        id: 'msg-2',
        content: 'How are you?',
        sender: { id: 2, username: 'user2' },
        timestamp: '2024-01-01T10:01:00Z',
        type: 'text',
      },
    ]);
  }),

  http.post(
    '*/api/v1/conversations/:id/messages',
    async ({ request, params }) => {
      const authHeader = request.headers.get('authorization');

      if (!authHeader || !authHeader.startsWith('Bearer ')) {
        return HttpResponse.json({ error: 'Unauthorized' }, { status: 401 });
      }

      const { id: _ } = params as { id: string };
      const body = (await request.json()) as { content: string; type?: string };

      return HttpResponse.json(
        {
          id: 'msg-new',
          content: body.content,
          sender: { id: 1, username: 'testuser' },
          timestamp: new Date().toISOString(),
          type: body.type || 'text',
        },
        { status: 201 },
      );
    },
  ),

  // CSRF token endpoint
  http.get('*/api/v1/csrf-token', () => {
    return HttpResponse.json({
      csrf_token: 'mock_csrf_token_123',
    });
  }),

  // Library endpoints
  http.get('*/api/v1/library/tracks', ({ request }) => {
    const authHeader = request.headers.get('authorization');

    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return HttpResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    return HttpResponse.json([
      {
        id: 'track-1',
        title: 'Test Track 1',
        artist: 'Test Artist',
        duration: 180,
        genre: 'Electronic',
        created_at: '2024-01-01T00:00:00Z',
      },
      {
        id: 'track-2',
        title: 'Test Track 2',
        artist: 'Test Artist',
        duration: 240,
        genre: 'Rock',
        created_at: '2024-01-01T00:00:00Z',
      },
    ]);
  }),

  http.post('*/api/v1/library/tracks', async ({ request }) => {
    const authHeader = request.headers.get('authorization');

    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return HttpResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const formData = await request.formData();
    const file = formData.get('file') as File;

    if (!file) {
      return HttpResponse.json({ error: 'No file provided' }, { status: 400 });
    }

    return HttpResponse.json(
      {
        id: 'track-new',
        title: file.name,
        artist: 'Unknown Artist',
        duration: 0,
        genre: 'Unknown',
        created_at: new Date().toISOString(),
      },
      { status: 201 },
    );
  }),

  // Health check
  http.get('*/api/v1/health', () => {
    return HttpResponse.json({
      status: 'healthy',
      timestamp: new Date().toISOString(),
      service: 'veza-backend-api',
      version: '1.0.0',
    });
  }),

  // Error simulation endpoints
  http.get('*/api/v1/error/500', () => {
    return HttpResponse.json(
      { error: 'Internal server error' },
      { status: 500 },
    );
  }),

  http.get('*/api/v1/error/404', () => {
    return HttpResponse.json({ error: 'Not found' }, { status: 404 });
  }),

  http.get('*/api/v1/error/timeout', () => {
    return new Promise(() => {
      // Simulate timeout by never resolving
    });
  }),
];

// Handlers pour les tests d'erreur
export const errorHandlers = [
  http.post('*/api/v1/auth/login', () => {
    return HttpResponse.json({ error: 'Service unavailable' }, { status: 503 });
  }),

  http.get('*/api/v1/users/profile', () => {
    return HttpResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }),
];

// Handlers pour les tests de performance
export const performanceHandlers = [
  http.get('*/api/v1/conversations', async () => {
    // Simulate slow response
    await new Promise((resolve) => setTimeout(resolve, 1000));

    return HttpResponse.json([
      {
        id: 'conv-1',
        name: 'General Chat',
        type: 'group',
        last_message: {
          id: 'msg-1',
          content: 'Hello, world!',
          sender: { id: 1, username: 'user1' },
          timestamp: '2024-01-01T10:00:00Z',
        },
        unread_count: 0,
        created_at: '2024-01-01T00:00:00Z',
      },
    ]);
  }),
];
