package com.example.cuida.data;

import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;
import androidx.annotation.NonNull;
import com.example.cuida.data.dao.UserDao;
import com.example.cuida.data.dao.AppointmentDao;
import com.example.cuida.data.dao.MedicationDao;
import com.example.cuida.data.model.User;
import com.example.cuida.data.model.Appointment;
import com.example.cuida.data.model.Medication;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Database(entities = { User.class, Appointment.class, Medication.class }, version = 3, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {

    public abstract UserDao userDao();

    public abstract AppointmentDao appointmentDao();

    public abstract MedicationDao medicationDao();

    private static volatile AppDatabase INSTANCE;
    private static final int NUMBER_OF_THREADS = 4;
    public static final ExecutorService databaseWriteExecutor = Executors.newFixedThreadPool(NUMBER_OF_THREADS);

    public static AppDatabase getDatabase(final Context context) {
        if (INSTANCE == null) {
            synchronized (AppDatabase.class) {
                if (INSTANCE == null) {
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            AppDatabase.class, "cuida_database")
                            .fallbackToDestructiveMigration()
                            .addCallback(sRoomDatabaseCallback)
                            .build();
                }
            }
        }
        return INSTANCE;
    }

    private static RoomDatabase.Callback sRoomDatabaseCallback = new RoomDatabase.Callback() {
        @Override
        public void onCreate(@NonNull SupportSQLiteDatabase db) {
            super.onCreate(db);
            databaseWriteExecutor.execute(() -> {
                // Populate the database in the background.

                MedicationDao medDao = INSTANCE.medicationDao();
                medDao.insert(new Medication("Paracetamol", "08:00", "1 comp", "Tomar com água"));
                medDao.insert(new Medication("Ibuprofeno", "14:00", "1 comp", "Após refeição"));
                medDao.insert(new Medication("Vitamina C", "20:00", "1 comp", "Antes de dormir"));

                AppointmentDao apptDao = INSTANCE.appointmentDao();
                apptDao.insert(new Appointment("Medicina Geral", "25/01/2026", "10:00", false));
                apptDao.insert(new Appointment("Cardiologia", "02/02/2026", "15:30", false));
                apptDao.insert(new Appointment("Oftalmologia", "10/01/2025", "09:00", true));
            });
        }
    };
}
