import { ArchiveLock } from '../../store/models/archive-lock';

const LOCK_ID = 'archive_job';
const LOCK_TTL_MS = 2 * 60 * 60 * 1000;

export function acquireArchiveLock(instanceId: string): Promise<boolean> {
  const { sequelize } = ArchiveLock;
  if (!sequelize) {
    return Promise.resolve(false);
  }
  const now = Date.now();
  const expiresAt = now + LOCK_TTL_MS;

  return sequelize.transaction(async (transaction) => {
    const existing = await ArchiveLock.findByPk(LOCK_ID, { transaction });
    if (!existing) {
      await ArchiveLock.create(
        {
          id: LOCK_ID,
          locked_by: instanceId,
          locked_at: now,
          expires_at: expiresAt,
        },
        { transaction }
      );
      return true;
    }

    if (!existing.expires_at || existing.expires_at <= now) {
      await existing.update(
        {
          locked_by: instanceId,
          locked_at: now,
          expires_at: expiresAt,
        },
        { transaction }
      );
      return true;
    }

    return false;
  });
}

export async function releaseArchiveLock(instanceId: string): Promise<void> {
  await ArchiveLock.update(
    { locked_by: null, locked_at: null, expires_at: null },
    { where: { id: LOCK_ID, locked_by: instanceId } }
  );
}
