import { Page, expect, request } from '@playwright/test';
import { RoleName, ROLES } from './helpers';

export class ApiHelper {
  private accessToken = '';

  constructor(private page: Page) {}

  async authenticate(role: RoleName = 'hospital_admin') {
    const config = ROLES[role];
    const response = await this.page.request.post('/accounts/token/', {
      data: {
        email: config.email,
        password: config.password,
      },
    });
    expect(response.status()).toBe(200);
    const body = await response.json();
    this.accessToken = body.access;
    return this.accessToken;
  }

  get token() {
    return this.accessToken;
  }

  private headers() {
    return { Authorization: `Bearer ${this.accessToken}` };
  }

  async get(path: string) {
    return this.page.request.get(path, { headers: this.headers() });
  }

  async post(path: string, data: any) {
    return this.page.request.post(path, { data, headers: this.headers() });
  }

  async patch(path: string, data: any) {
    return this.page.request.patch(path, { data, headers: this.headers() });
  }

  async delete(path: string) {
    return this.page.request.delete(path, { headers: this.headers() });
  }

  async createComplaint(data?: Partial<any>) {
    const hospital_id = '7e4d08ce-2e0a-4184-8297-7acd418184a6';
    const dueDate = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
    const ts = Date.now();
    const payload = {
      patient_name: `E2E Test Patient ${ts}`,
      national_id: `E2E${ts}`,
      relation_to_patient: 'patient',
      incident_date: '2026-01-15',
      description: 'E2E automated test complaint - please ignore',
      hospital: hospital_id,
      complaint_type: 'complaint',
      title: `E2E Test Complaint ${ts}`,
      due_at: dueDate,
      ...data,
    };
    const resp = await this.post('/complaints/api/complaints/', payload);
    return { response: resp, body: await resp.json().catch(() => null) };
  }

  async createInquiry(data?: Partial<any>) {
    const hospital_id = '7e4d08ce-2e0a-4184-8297-7acd418184a6';
    const payload = {
      contact_name: `E2E Test Contact ${Date.now()}`,
      contact_phone: '0500000001',
      contact_email: `e2e-test-${Date.now()}@test.com`,
      subject: `E2E automated test inquiry ${Date.now()}`,
      message: 'E2E automated test inquiry - please ignore',
      hospital: hospital_id,
      category: 'general',
      ...data,
    };
    const resp = await this.post('/complaints/api/inquiries/', payload);
    return { response: resp, body: await resp.json().catch(() => null) };
  }

  async activateComplaint(id: string) {
    return this.post(`/complaints/api/complaints/${id}/activate/`, {});
  }

  async changeComplaintStatus(id: string, status: string, data?: Record<string, any>) {
    return this.post(`/complaints/api/complaints/${id}/change_status/`, { status, ...data });
  }

  async addComplaintNote(id: string, note: string) {
    return this.post(`/complaints/api/complaints/${id}/add_note/`, { note });
  }

  async respondToInquiry(id: string, response: string) {
    return this.post(`/complaints/api/inquiries/${id}/respond/`, { response });
  }

  async setDueAtPast(entityType: 'complaints' | 'inquiries', id: string, daysAgo: number = 7) {
    const pastDate = new Date(Date.now() - daysAgo * 24 * 60 * 60 * 1000).toISOString();
    return this.patch(`/complaints/api/${entityType}/${id}/`, { due_at: pastDate });
  }

  async getEntityDetail(entityType: 'complaints' | 'inquiries', id: string) {
    const resp = await this.get(`/complaints/api/${entityType}/${id}/`);
    return { response: resp, body: await resp.json().catch(() => null) };
  }
}

export async function getCsrfToken(page: Page): Promise<string> {
  return page.evaluate(() => {
    const match = document.cookie.match(/csrftoken=([^;]+)/);
    return match ? match[1] : '';
  });
}

export async function sessionPost(page: Page, url: string, data: Record<string, string>) {
  const csrfToken = await getCsrfToken(page);
  return page.request.post(url, {
    form: { csrfmiddlewaretoken: csrfToken, ...data },
    headers: {
      'X-CSRFToken': csrfToken,
      Referer: page.url(),
    },
  });
}

export const HOSPITAL_ID = '7e4d08ce-2e0a-4184-8297-7acd418184a6';
export const DEPT_ID = 'db141bc8-fe52-43bf-a162-b8872e4f8488';
export const LOCATION_ID = '49';
