import { Client, Account, Databases, Query, ID } from "appwrite";

const client = new Client()
  .setEndpoint(process.env.NEXT_PUBLIC_APPWRITE_ENDPOINT)
  .setProject(process.env.NEXT_PUBLIC_APPWRITE_PROJECT_ID);

const account = new Account(client);
const databases = new Databases(client);


const DATABASE_ID = process.env.NEXT_PUBLIC_APPWRITE_DATABASE_ID;
const COLLECTION_ID = process.env.NEXT_PUBLIC_APPWRITE_COLLECTION_ID;
const USERS_COLLECTION_ID = process.env.NEXT_PUBLIC_APPWRITE_USERS_COLLECTION_ID;

// Initialize with proper schema
async function initDatabase() {
  try {
    // Main tokens collection
    await databases.createCollection(
      DATABASE_ID,
      COLLECTION_ID,
      "Token Management"
    );

    // Add attributes matching new schema
    await databases.createStringAttribute(
      DATABASE_ID,
      COLLECTION_ID,
      "tokenId",
      20,
      true
    );
    
    await databases.createDatetimeAttribute(
      DATABASE_ID,
      COLLECTION_ID,
      "date",
      true
    );
    
    await databases.createStringAttribute(
      DATABASE_ID,
      COLLECTION_ID,
      "patientName",
      100,
      true
    );
    
    await databases.createStringAttribute(
      DATABASE_ID,
      COLLECTION_ID,
      "patientId",
      50,
      false
    );
    
    await databases.createEnumAttribute(
      DATABASE_ID,
      COLLECTION_ID,
      "bookedBy",
      ["self", "staff"]
    );
    
    await databases.createEnumAttribute(
      DATABASE_ID,
      COLLECTION_ID,
      "status",
      ["booked", "done", "missed"]
    );

    // Settings collection
    await databases.createCollection(
      DATABASE_ID,
      'settings',
      "System Settings"
    );
    
    await databases.createIntegerAttribute(
      DATABASE_ID,
      'settings',
      "avgConsultationTime",
      true
    );

  } catch (error) {
    console.error("Initialization error:", error);
    if (!error.message.includes('already exists')) {
      throw error;
    }
  }
}

// Date-based token generator
// lib/appwrite.js
 async function generateTokenNumber(date) {
  // Step 1: Get all documents for the selected date
  const response = await databases.listDocuments(
    DATABASE_ID,
    COLLECTION_ID,
    [Query.equal("date", date)]
  );

  // Step 2: Get the next token count
  const nextNumber = response.total + 1;

  // Step 3: Pad the number with zeros (e.g., 1 => 001)
  const paddedToken = String(nextNumber).padStart(3, '0');

  return paddedToken;
}
// 🔐 Get User Role from `users` collection
async function getUserRole() {
  try {
    const user = await account.get();
    const userId = user.$id;

    const response = await databases.listDocuments(
      DATABASE_ID,
      USERS_COLLECTION_ID,
      [Query.equal("userId", userId)]
    );

    if (response.total === 0) {
      throw new Error("User not found in users collection.");
    }

    return response.documents[0].role;
  } catch (error) {
    console.error("Error fetching role:", error.message);
    return null;
  }
}
export {
  getUserRole,
  client,
  account,
  databases,
  DATABASE_ID,
  COLLECTION_ID,
  USERS_COLLECTION_ID,
  Query,
  ID,
  initDatabase,
  generateTokenNumber,
};