import { CalendarProvider, ExternalCalendar, BusyInterval, TokenPair } from './CalendarProvider.interface';
import { CalendarConnection } from '../../models/entities/CalendarConnection.entity';
import { Booking } from '../../models/entities/Booking.entity';
import { EventType } from '../../models/entities/EventType.entity';
import { encrypt, decrypt } from '../../utils/crypto';
import { generateUuid } from '../../utils/uuid';

export class AppleCalendarProvider implements CalendarProvider {
  async listCalendars(_connection: CalendarConnection): Promise<ExternalCalendar[]> {
    return [{ externalId: 'default', name: 'iCloud Calendar' }];
  }

  async getFreeBusy(_connection: CalendarConnection, _from: Date, _to: Date): Promise<BusyInterval[]> {
    // CalDAV implementation — requires discovered calendar URL stored in calendarConfig
    return [];
  }

  async createEvent(
    _connection: CalendarConnection,
    booking: Booking,
    eventType: EventType,
  ): Promise<{ eventId: string; calendarId: string }> {
    const eventId = generateUuid();
    // Full CalDAV PUT would go here using stored credentials
    return { eventId, calendarId: 'default' };
  }

  async updateEvent(
    _connection: CalendarConnection,
    _calendarId: string,
    _eventId: string,
    _booking: Booking,
    _eventType: EventType,
  ): Promise<void> {
    // CalDAV update
  }

  async deleteEvent(
    _connection: CalendarConnection,
    _calendarId: string,
    _eventId: string,
  ): Promise<void> {
    // CalDAV delete
  }

  async refreshToken(_connection: CalendarConnection): Promise<TokenPair> {
    throw new Error('Apple uses app-specific passwords, not refresh tokens');
  }

  storeCredentials(appleId: string, appPassword: string) {
    return {
      accessTokenEnc: encrypt(`${appleId}:${appPassword}`),
      refreshTokenEnc: null,
    };
  }

  getCredentials(connection: CalendarConnection): { appleId: string; password: string } {
    const decoded = decrypt(connection.accessTokenEnc!);
    const [appleId, password] = decoded.split(':');
    return { appleId, password };
  }
}
