import { db } from '../config/database.js';
import { companies, companyReminders } from '../db/schema.js';
import { eq, desc } from 'drizzle-orm';
import { NotFoundError, BadRequestError } from '../utils/errors.js';

const ensureCompanyExists = async (companyId) => {
  const [company] = await db
    .select({ id: companies.id })
    .from(companies)
    .where(eq(companies.id, companyId))
    .limit(1);

  if (!company) {
    throw new NotFoundError('Firma nenájdená');
  }
};

const getReminderById = async (reminderId) => {
  const [reminder] = await db
    .select()
    .from(companyReminders)
    .where(eq(companyReminders.id, reminderId))
    .limit(1);

  if (!reminder) {
    throw new NotFoundError('Reminder nenájdený');
  }

  return reminder;
};

export const getRemindersByCompanyId = async (companyId) => {
  await ensureCompanyExists(companyId);

  const reminders = await db
    .select()
    .from(companyReminders)
    .where(eq(companyReminders.companyId, companyId))
    .orderBy(desc(companyReminders.createdAt));

  return reminders;
};

export const createReminder = async (companyId, data) => {
  await ensureCompanyExists(companyId);

  const description = data.description?.trim();
  if (!description) {
    throw new BadRequestError('Popis pripomienky je povinný');
  }

  const [reminder] = await db
    .insert(companyReminders)
    .values({
      companyId,
      description,
      isChecked: data.isChecked ?? false,
    })
    .returning();

  return reminder;
};

export const updateReminder = async (companyId, reminderId, data) => {
  const reminder = await getReminderById(reminderId);

  if (reminder.companyId !== companyId) {
    throw new NotFoundError('Reminder nenájdený');
  }

  const trimmedDescription = data.description !== undefined
    ? data.description.trim()
    : reminder.description;

  if (data.description !== undefined && !trimmedDescription) {
    throw new BadRequestError('Popis pripomienky je povinný');
  }

  const [updatedReminder] = await db
    .update(companyReminders)
    .set({
      description: trimmedDescription,
      isChecked: data.isChecked !== undefined ? data.isChecked : reminder.isChecked,
      updatedAt: new Date(),
    })
    .where(eq(companyReminders.id, reminderId))
    .returning();

  return updatedReminder;
};

export const deleteReminder = async (companyId, reminderId) => {
  const reminder = await getReminderById(reminderId);

  if (reminder.companyId !== companyId) {
    throw new NotFoundError('Reminder nenájdený');
  }

  await db.delete(companyReminders).where(eq(companyReminders.id, reminderId));

  return { success: true, message: 'Reminder bol odstránený' };
};
