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}` };
}

export interface AvailabilityRequest {
  doctorId: string;
  dayOfWeek: 'MONDAY' | 'TUESDAY' | 'WEDNESDAY' | 'THURSDAY' | 'FRIDAY' | 'SATURDAY' | 'SUNDAY';
  startTime: string;
  endTime: string;
}

export interface BulkAvailabilityRequest {
  doctorId: string;
  availabilities: {
    dayOfWeek: 'MONDAY' | 'TUESDAY' | 'WEDNESDAY' | 'THURSDAY' | 'FRIDAY' | 'SATURDAY' | 'SUNDAY';
    startTime: string;
    endTime: string;
  }[];
}

export interface AvailabilityResponse {
  id: string;
  doctorId: string;
  dayOfWeek: string;
  startTime: string;
  endTime: string;
  isAvailable: boolean;
}

@Injectable({ providedIn: 'root' })
export class AvailabilityService {
  async getDoctorAvailability(doctorId: string): Promise<AvailabilityResponse[]> {
    const res = await axios.get(`${BASE_URL}/api/v3/availability/doctor/${doctorId}`, { headers: authHeaders() });
    return res.data;
  }

  async createAvailability(request: AvailabilityRequest): Promise<AvailabilityResponse> {
    const res = await axios.post(`${BASE_URL}/api/v3/availability`, request, { headers: authHeaders() });
    return res.data;
  }

  async updateAvailability(availabilityId: string, request: Partial<AvailabilityRequest>): Promise<AvailabilityResponse> {
    const res = await axios.patch(`${BASE_URL}/api/v3/availability/${availabilityId}`, request, { headers: authHeaders() });
    return res.data;
  }

  async deleteAvailability(availabilityId: string): Promise<void> {
    await axios.delete(`${BASE_URL}/api/v3/availability/${availabilityId}`, { headers: authHeaders() });
  }

  async getAvailabilityByDay(doctorId: string, dayOfWeek: string): Promise<AvailabilityResponse[]> {
    const res = await axios.get(`${BASE_URL}/api/v3/availability/doctor/${doctorId}/day/${dayOfWeek}`, { headers: authHeaders() });
    return res.data;
  }

  async getActiveAvailability(doctorId: string): Promise<AvailabilityResponse[]> {
    const res = await axios.get(`${BASE_URL}/api/v3/availability/doctor/${doctorId}/active`, { headers: authHeaders() });
    return res.data;
  }

  async createBulkAvailability(request: BulkAvailabilityRequest): Promise<AvailabilityResponse[]> {
    const res = await axios.post(`${BASE_URL}/api/v3/availability/bulk`, request, { headers: authHeaders() });
    return res.data;
  }

  async deleteAllDoctorAvailability(doctorId: string): Promise<void> {
    await axios.delete(`${BASE_URL}/api/v3/availability/doctor/${doctorId}`, { headers: authHeaders() });
  }
}

