/**
 * PocketBase Service - PocketBase integration
 */

import PocketBase from 'pocketbase';
import { env } from '../config/env';
import type { PocketBaseUser } from '@shared/types/auth';
import type { Job, StickyNote } from '@shared/types/job';

class PocketBaseService {
  private client: PocketBase;

  constructor() {
    this.client = new PocketBase(env.POCKETBASE_URL);
  }

  /**
   * Get PocketBase client instance
   */
  get pb(): PocketBase {
    return this.client;
  }

  /**
   * Authenticate with token
   */
  async authenticateWithToken(token: string): Promise<PocketBaseUser | null> {
    try {
      this.client.authStore.save(token, null);
      const authData = await this.client.collection('users').authRefresh();
      return authData.record as unknown as PocketBaseUser;
    } catch (err) {
      console.error('[PocketBase] Auth with token failed:', err);
      return null;
    }
  }

  /**
   * Refresh token using refresh token
   */
  async refreshToken(refreshToken: string): Promise<{ token: string; refreshToken: string }> {
    try {
      // PocketBase SDK handles refresh internally
      // We need to set the token first and then refresh
      this.client.authStore.save(refreshToken, null);
      const authData = await this.client.collection('users').authRefresh();
      
      return {
        token: authData.token,
        refreshToken: authData.token, // PocketBase uses same token for refresh
      };
    } catch (err) {
      console.error('[PocketBase] Token refresh failed:', err);
      throw err;
    }
  }

  /**
   * Get user by ID
   */
  async getUser(userId: string): Promise<PocketBaseUser | null> {
    try {
      const record = await this.client.collection('users').getOne(userId);
      return record as unknown as PocketBaseUser;
    } catch (err) {
      console.error('[PocketBase] Get user failed:', err);
      return null;
    }
  }

  /**
   * Get all jobs (with optional filters)
   */
  async getJobs(options?: {
    page?: number;
    perPage?: number;
    filter?: string;
    sort?: string;
  }): Promise<{ items: Job[]; totalItems: number; totalPages: number }> {
    try {
      const result = await this.client.collection('jobs').getList(
        options?.page ?? 1,
        options?.perPage ?? 50,
        {
          filter: options?.filter,
          sort: options?.sort ?? '-created',
        }
      );
      
      return {
        items: result.items as unknown as Job[],
        totalItems: result.totalItems,
        totalPages: result.totalPages,
      };
    } catch (err) {
      console.error('[PocketBase] Get jobs failed:', err);
      throw err;
    }
  }

  /**
   * Get single job by ID
   */
  async getJob(jobId: string): Promise<Job | null> {
    try {
      const record = await this.client.collection('jobs').getOne(jobId);
      return record as unknown as Job;
    } catch (err) {
      console.error('[PocketBase] Get job failed:', err);
      return null;
    }
  }

  /**
   * Get notes for a job
   */
  async getJobNotes(jobId: string): Promise<StickyNote[]> {
    try {
      const result = await this.client.collection('sticky_notes').getFullList({
        filter: `job_id = "${jobId}"`,
        sort: '-created',
      });
      return result as unknown as StickyNote[];
    } catch (err) {
      console.error('[PocketBase] Get job notes failed:', err);
      return [];
    }
  }

  /**
   * Create a sticky note
   */
  async createNote(note: Omit<StickyNote, 'id' | 'created' | 'updated'>): Promise<StickyNote | null> {
    try {
      const record = await this.client.collection('sticky_notes').create(note);
      return record as unknown as StickyNote;
    } catch (err) {
      console.error('[PocketBase] Create note failed:', err);
      return null;
    }
  }

  /**
   * Update a sticky note
   */
  async updateNote(noteId: string, data: Partial<StickyNote>): Promise<StickyNote | null> {
    try {
      const record = await this.client.collection('sticky_notes').update(noteId, data);
      return record as unknown as StickyNote;
    } catch (err) {
      console.error('[PocketBase] Update note failed:', err);
      return null;
    }
  }

  /**
   * Delete a sticky note
   */
  async deleteNote(noteId: string): Promise<boolean> {
    try {
      await this.client.collection('sticky_notes').delete(noteId);
      return true;
    } catch (err) {
      console.error('[PocketBase] Delete note failed:', err);
      return false;
    }
  }

  /**
   * Clear auth state
   */
  clearAuth(): void {
    this.client.authStore.clear();
  }
}

export const pocketbaseService = new PocketBaseService();
