import { Injectable } from '@angular/core';
import axios from 'axios';

import { BASE_URL } from '../config/api.config';

function authHeaders() {
  const token = localStorage.getItem('jwtToken');
  return { Authorization: `Bearer ${token}` };
}

@Injectable({ providedIn: 'root' })
export class AdminService {
  async getStats() {
    const res = await axios.get(`${BASE_URL}/api/v3/admin/stats`, { headers: authHeaders() });
    return res.data;
  }
  async getUsers() {
    const res = await axios.get(`${BASE_URL}/api/v3/admin/users`, { headers: authHeaders() });
    return res.data;
  }
  async getDoctors() {
    const res = await axios.get(`${BASE_URL}/api/v3/admin/doctors`, { headers: authHeaders() });
    return res.data;
  }
  async getPatients() {
    const res = await axios.get(`${BASE_URL}/api/v3/admin/patients`, { headers: authHeaders() });
    return res.data;
  }
  async activateUser(email: string) {
    const res = await axios.patch(`${BASE_URL}/api/v3/admin/users/${encodeURIComponent(email)}/activate`, {}, { headers: authHeaders() });
    return res.data;
  }
  async deactivateUser(email: string) {
    const res = await axios.patch(`${BASE_URL}/api/v3/admin/users/${encodeURIComponent(email)}/deactivate`, {}, { headers: authHeaders() });
    return res.data;
  }
  async deleteUser(email: string) {
    await axios.delete(`${BASE_URL}/api/v3/admin/users/${encodeURIComponent(email)}`, { headers: authHeaders() });
  }
  async verifyDoctor(medicalLicenseNumber: string) {
    await axios.patch(`${BASE_URL}/api/v3/admin/doctors/${encodeURIComponent(medicalLicenseNumber)}/verify`, {}, { headers: authHeaders() });
  }
  async unverifyDoctor(medicalLicenseNumber: string) {
    await axios.patch(`${BASE_URL}/api/v3/admin/doctors/${encodeURIComponent(medicalLicenseNumber)}/unverify`, {}, { headers: authHeaders() });
  }
  async deleteAppointment(appointmentId: string) {
    await axios.delete(`${BASE_URL}/api/v3/appointments/${appointmentId}`, { headers: authHeaders() });
  }
  async getAllAppointments() {
    const res = await axios.get(`${BASE_URL}/api/v3/admin/appointments`, { headers: authHeaders() });
    return res.data;
  }

  async getUsersPaginated(page: number = 0, size: number = 20, sortBy?: string, direction: string = 'ASC') {
    const params: any = { page, size, direction };
    if (sortBy) params.sortBy = sortBy;
    const res = await axios.get(`${BASE_URL}/api/v3/admin/users/paginated`, { params, headers: authHeaders() });
    return res.data;
  }

  async getMetrics() {
    const res = await axios.get(`${BASE_URL}/api/v3/admin/metrics`, { headers: authHeaders() });
    return res.data;
  }
}
