import { db } from './db.js';

export interface GuildSettings {
  guildId: string;
  welcomeEnabled: boolean;
  welcomeChannelId: string | null;
  welcomeMessage: string;
  autoRoleId: string | null;
  logChannelId: string | null;
}

const defaultSettings = (guildId: string): GuildSettings => ({
  guildId,
  welcomeEnabled: false,
  welcomeChannelId: null,
  welcomeMessage: 'Bienvenue {user} sur **{server}** !',
  autoRoleId: null,
  logChannelId: null
});

export function getGuildSettings(guildId: string): GuildSettings {
  const row = db.prepare(`
    SELECT guild_id, welcome_enabled, welcome_channel_id, welcome_message, auto_role_id, log_channel_id
    FROM guild_settings WHERE guild_id = ?
  `).get(guildId) as {
    guild_id: string;
    welcome_enabled: number;
    welcome_channel_id: string | null;
    welcome_message: string;
    auto_role_id: string | null;
    log_channel_id: string | null;
  } | undefined;

  if (!row) return defaultSettings(guildId);

  return {
    guildId: row.guild_id,
    welcomeEnabled: Boolean(row.welcome_enabled),
    welcomeChannelId: row.welcome_channel_id,
    welcomeMessage: row.welcome_message,
    autoRoleId: row.auto_role_id,
    logChannelId: row.log_channel_id
  };
}

export function saveGuildSettings(settings: GuildSettings): void {
  db.prepare(`
    INSERT INTO guild_settings (
      guild_id, welcome_enabled, welcome_channel_id, welcome_message, auto_role_id, log_channel_id, updated_at
    ) VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
    ON CONFLICT(guild_id) DO UPDATE SET
      welcome_enabled = excluded.welcome_enabled,
      welcome_channel_id = excluded.welcome_channel_id,
      welcome_message = excluded.welcome_message,
      auto_role_id = excluded.auto_role_id,
      log_channel_id = excluded.log_channel_id,
      updated_at = CURRENT_TIMESTAMP
  `).run(
    settings.guildId,
    settings.welcomeEnabled ? 1 : 0,
    settings.welcomeChannelId,
    settings.welcomeMessage,
    settings.autoRoleId,
    settings.logChannelId
  );
}

export function addAuditLog(input: {
  guildId: string;
  actorId: string;
  actorName: string;
  action: string;
  details?: string;
}): void {
  db.prepare(`
    INSERT INTO audit_logs (guild_id, actor_id, actor_name, action, details)
    VALUES (?, ?, ?, ?, ?)
  `).run(input.guildId, input.actorId, input.actorName, input.action, input.details ?? null);
}

export function getAuditLogs(guildId: string, limit = 12) {
  return db.prepare(`
    SELECT actor_name AS actorName, action, details, created_at AS createdAt
    FROM audit_logs
    WHERE guild_id = ?
    ORDER BY id DESC
    LIMIT ?
  `).all(guildId, limit) as Array<{
    actorName: string;
    action: string;
    details: string | null;
    createdAt: string;
  }>;
}
