import type { Page, Route } from '@playwright/test';
import { agentUser, superAdminUser } from '../fixtures/users';

type MockUser = typeof agentUser;

function json(route: Route, body: unknown, status = 200): Promise<void> {
  return route.fulfill({
    status,
    contentType: 'application/json',
    body: JSON.stringify(body),
  });
}

export async function registerBaseApiMocks(page: Page, user: MockUser = agentUser): Promise<void> {
  await Promise.all([
    page.route('**/sanctum/csrf-cookie', (route) => route.fulfill({ status: 204, body: '' })),

    page.route('**/api/v1/auth/me', (route) => json(route, { data: user })),
    page.route('**/api/v1/auth/logout', (route) => json(route, { message: 'ok' })),

    page.route('**/api/v1/auth/request-otp', (route) =>
      json(route, { message: 'If your email is registered, you will receive a login code shortly.' }),
    ),

    page.route('**/api/v1/auth/verify-otp', (route) => json(route, { data: user })),

    page.route('**/api/v1/auth/request-magic-link', (route) =>
      json(route, { message: 'Magic link sent if registered.' }),
    ),

    page.route('**/api/v1/auth/verify-magic-link**', (route) => json(route, { data: user })),

    page.route('**/api/v1/auth/accept-invite', (route) => json(route, { data: user })),

    page.route('**/api/v1/dashboard/overview**', (route) =>
      json(route, {
        data: {
          stats: { total: 2, open: 1, resolved: 1, overdue: 0 },
          charts: {},
          recent_activity: [],
        },
      }),
    ),

    page.route('**/api/v1/tickets**', async (route) => {
      const method = route.request().method();
      if (method === 'GET') {
        return json(route, {
          data: [
            {
              id: 'ticket-1',
              ticket_number: 'TKT-001',
              subject: 'E2E ticket',
              status: { name_en: 'Open', name_ar: 'مفتوح', color: '#22c55e' },
              priority: { name_en: 'Normal', name_ar: 'عادي', color: '#6366f1' },
            },
          ],
          meta: { current_page: 1, last_page: 1, total: 1 },
        });
      }
      if (method === 'POST') {
        return json(route, { data: { id: 'ticket-new', ticket_number: 'TKT-NEW' } }, 201);
      }
      return json(route, { data: {} });
    }),

    page.route('**/api/v1/departments**', async (route) => {
      const method = route.request().method();
      if (method === 'GET') {
        return json(route, { data: user.departments });
      }
      if (method === 'POST') {
        return json(route, { data: { id: 'dept-new', name: 'New Dept', code: 'NEW', is_active: true } }, 201);
      }
      return json(route, { data: user.departments[0] });
    }),

    page.route('**/api/v1/admin/invites**', async (route) => {
      const method = route.request().method();
      if (method === 'GET') {
        return json(route, { data: [] });
      }
      if (method === 'POST') {
        return json(route, { data: { id: 'invite-1', email: 'invite@test.com' } }, 201);
      }
      return json(route, { data: {} });
    }),

    page.route('**/api/v1/sla-policies**', async (route) => {
      const method = route.request().method();
      if (method === 'GET') {
        return json(route, { data: [] });
      }
      if (method === 'POST') {
        return json(route, { data: { id: 'sla-1', name_en: 'Standard', name_ar: 'قياسي' } }, 201);
      }
      return json(route, { data: {} });
    }),

    page.route('**/api/v1/settings**', async (route) => {
      const method = route.request().method();
      if (method === 'GET') {
        return json(route, {
          data: {
            'general.app_name': {
              key: 'general.app_name',
              value: 'MV HelpDesk',
              group: 'general',
              label: 'App name',
              type: 'string',
              default_value: 'MV HelpDesk',
              is_public: true,
              is_encrypted: false,
              source: 'department',
              source_scope_id: user.departments[0]?.id ?? null,
            },
          },
          meta: { department_id: user.departments[0]?.id },
        });
      }
      return json(route, { success: true, data: { key: 'general.app_name', value: 'Updated' } });
    }),

    page.route('**/api/v1/setting-definitions**', (route) =>
      json(route, { data: ['general', 'ticketing'] }),
    ),

    page.route('**/api/v1/notifications**', async (route) => {
      const method = route.request().method();
      const url = route.request().url();
      if (method === 'GET') {
        return json(route, {
          data: [{ id: 'n1', title: 'New ticket', read_at: null, created_at: new Date().toISOString() }],
        });
      }
      if (url.includes('/read') || method === 'PATCH') {
        return json(route, { data: { id: 'n1', read_at: new Date().toISOString() } });
      }
      return json(route, { data: {} });
    }),

    page.route('**/api/v1/profile/sessions**', async (route) => {
      const method = route.request().method();
      if (method === 'GET') {
        return json(route, {
          data: [
            { id: 'sess-1', is_current: true, ip_address: '127.0.0.1', user_agent: 'Playwright', last_active_at: new Date().toISOString() },
            { id: 'sess-2', is_current: false, ip_address: '10.0.0.2', user_agent: 'Other', last_active_at: new Date().toISOString() },
          ],
        });
      }
      if (method === 'DELETE') {
        return json(route, { message: 'Session revoked' });
      }
      return json(route, { data: {} });
    }),

    page.route('**/api/v1/**/attachments**', (route) =>
      json(route, { data: { id: 'att-1', file_name: 'test.txt' } }, 201),
    ),

    page.route('**/api/v1/**/replies**', (route) =>
      json(route, { data: { id: 'reply-1', body: 'Reply body' } }, 201),
    ),

    page.route('**/api/v1/companies**', (route) => json(route, { data: [] })),
    page.route('**/api/v1/users**', (route) => json(route, { data: [] })),
    page.route('**/api/v1/categories**', (route) => json(route, { data: [] })),
    page.route('**/api/v1/roles**', (route) => json(route, { data: [] })),
    page.route('**/api/v1/permissions**', (route) => json(route, { data: [] })),
    page.route('**/api/v1/audit-logs**', (route) => json(route, { data: [], meta: { total: 0 } })),
    page.route('**/api/v1/notification-templates**', (route) => json(route, { data: [] })),
    page.route('**/api/v1/ticket-statuses**', (route) => json(route, { data: [] })),
    page.route('**/api/v1/ticket-priorities**', (route) => json(route, { data: [] })),
    page.route('**/api/v1/search**', (route) => json(route, { data: { tickets: [], total: 0 } })),
    page.route('**/api/v1/departments/*/ticket-form-options**', (route) =>
      json(route, {
        data: {
          categories: [],
          priorities: [{ id: 'p1', name_en: 'Normal', name_ar: 'عادي' }],
          statuses: [{ id: 's1', name_en: 'Open', name_ar: 'مفتوح' }],
        },
      }),
    ),
  ]);
}

export { superAdminUser };
