import PocketBase from 'pocketbase';

async function createVisitsCollection() {
  const pb = new PocketBase('http://localhost:8090');

  // Authenticate as superuser (required for creating collections)
  try {
    await pb.collection("_superusers").authWithPassword('azeem.fidahusein@gmail.com', 'azsxdcazsxdc');
    console.log('Authenticated as superuser');
  } catch (error) {
    console.error('Failed to authenticate as superuser:', error.message);
    console.error('Make sure your PocketBase instance has a superuser with email "test@example.com" and password "1234567890"');
    throw error;
  }

  const collectionData = {
    name: 'visits',
    type: 'base',
    fields: [
      {
        name: 'segment_index',
        type: 'number',
        required: true
      },
      {
        name: 'hierarchyLevel',
        type: 'number',
        required: false
      },
      {
        name: 'visit_probability',
        type: 'number',
        required: true
      },
      {
        name: 'top_place_id',
        type: 'text',
        required: false,
        max: 255
      },
      {
        name: 'top_semantic_type',
        type: 'text',
        required: false,
        max: 100
      },
      {
        name: 'top_probability',
        type: 'number',
        required: false
      },
      {
        name: 'top_lat',
        type: 'number',
        required: false
      },
      {
        name: 'top_lon',
        type: 'number',
        required: false
      },
      {
        name: 'startTime',
        type: 'date',
        required: true
      },
      {
        name: 'endTime',
        type: 'date',
        required: true
      }
    ],
    indexes: [
      'CREATE INDEX idx_visits_segment_index ON visits (segment_index)',
      'CREATE INDEX idx_visits_start_time ON visits (startTime)',
      'CREATE INDEX idx_visits_place_id ON visits (top_place_id)'
    ],
    listRule: '',
    viewRule: '',
    createRule: '',
    updateRule: '',
    deleteRule: ''
  };

  try {
    console.log('Creating visits collection...');
    const collection = await pb.collections.create(collectionData);
    console.log('Collection created successfully:', collection.name);
    return collection;
  } catch (error) {
    if (error.message.includes('already exists')) {
      console.log('Collection "visits" already exists');
    } else {
      console.error('Error creating collection:', error);
      throw error;
    }
  }
}

// Check if this file is being run directly
if (import.meta.url === `file://${process.argv[1]}`) {
  createVisitsCollection()
    .then(() => {
      console.log('Script completed successfully');
      process.exit(0);
    })
    .catch((error) => {
      console.error('Script failed:', error);
      process.exit(1);
    });
}

export { createVisitsCollection };