import { readdirSync } from 'fs';
import path from 'path';
import { fileURLToPath, pathToFileURL } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

export async function loadCommands(client) {
  const commandsDir = path.join(__dirname, '..', 'commands');
  const files = readdirSync(commandsDir).filter(f => f.endsWith('.js'));
  for (const file of files) {
    const mod = await import(pathToFileURL(path.join(commandsDir, file)).href);
    const cmd = mod.default;
    if (cmd?.data?.name) {
      client.commands.set(cmd.data.name, cmd);
      console.log(`  ↳ command: /${cmd.data.name}`);
    }
  }
  console.log(`✅ Loaded ${client.commands.size} commands`);
}

export async function loadEvents(client) {
  const eventsDir = path.join(__dirname, '..', 'events');
  const files = readdirSync(eventsDir).filter(f => f.endsWith('.js'));
  for (const file of files) {
    const mod = await import(pathToFileURL(path.join(eventsDir, file)).href);
    const ev = mod.default;
    if (!ev?.name) continue;
    if (ev.once) client.once(ev.name, (...args) => ev.execute(...args, client));
    else client.on(ev.name, (...args) => ev.execute(...args, client));
    console.log(`  ↳ event: ${ev.name}`);
  }
  console.log(`✅ Loaded ${files.length} events`);
}

export function isOwner(userId) {
  return userId === process.env.OWNER_ID;
}

export function isStaff(member, staffRoleId) {
  if (!member) return false;
  if (member.permissions?.has?.('Administrator')) return true;
  if (staffRoleId && member.roles?.cache?.has?.(staffRoleId)) return true;
  return false;
}
