/**
 * Auth Repository
 * Handles CRUD operations for users and settings tables
 */

import { BaseRepository } from '../base.repository.ts';
import type { IUser } from '../../types.ts';

export class AuthRepository extends BaseRepository {
  // ============ Users ============

  async createUser(user: Omit<IUser, 'id'>): Promise<IUser> {
    const now = Date.now();
    this.query(
      'INSERT INTO users (username, password_hash, role, created_at, updated_at) VALUES (?, ?, ?, ?, ?)',
      [user.username, user.passwordHash, user.role, now, now]
    );

    return this.getUserByUsername(user.username)!;
  }

  getUserByUsername(username: string): IUser | null {
    const rows = this.query('SELECT * FROM users WHERE username = ?', [username]);
    return rows.length > 0 ? this.rowToUser(rows[0]) : null;
  }

  getAllUsers(): IUser[] {
    const rows = this.query('SELECT * FROM users ORDER BY created_at DESC');
    return rows.map((row) => this.rowToUser(row));
  }

  updateUserPassword(username: string, passwordHash: string): void {
    this.query('UPDATE users SET password_hash = ?, updated_at = ? WHERE username = ?', [
      passwordHash,
      Date.now(),
      username,
    ]);
  }

  deleteUser(username: string): void {
    this.query('DELETE FROM users WHERE username = ?', [username]);
  }

  private rowToUser(row: any): IUser {
    return {
      id: Number(row.id || row[0]),
      username: String(row.username || row[1]),
      passwordHash: String(row.password_hash || row[2]),
      role: String(row.role || row[3]) as IUser['role'],
      createdAt: Number(row.created_at || row[4]),
      updatedAt: Number(row.updated_at || row[5]),
    };
  }

  // ============ Settings ============

  getSetting(key: string): string | null {
    const rows = this.query('SELECT value FROM settings WHERE key = ?', [key]);
    if (rows.length === 0) return null;

    const value = (rows[0] as any).value || rows[0][0];
    return value ? String(value) : null;
  }

  setSetting(key: string, value: string): void {
    const now = Date.now();
    this.query(
      'INSERT OR REPLACE INTO settings (key, value, updated_at) VALUES (?, ?, ?)',
      [key, value, now]
    );
  }

  deleteSetting(key: string): void {
    this.query('DELETE FROM settings WHERE key = ?', [key]);
  }

  getAllSettings(): Record<string, string> {
    const rows = this.query('SELECT key, value FROM settings');
    const settings: Record<string, string> = {};
    for (const row of rows) {
      const key = (row as any).key || row[0];
      const value = (row as any).value || row[1];
      settings[String(key)] = String(value);
    }
    return settings;
  }

  getSecretSetting(key: string): string | null {
    const rows = this.query('SELECT value FROM secret_settings WHERE key = ?', [key]);
    if (rows.length === 0) return null;

    const value = (rows[0] as any).value || rows[0][0];
    return value ? String(value) : null;
  }

  setSecretSetting(key: string, value: string): void {
    const now = Date.now();
    this.query(
      'INSERT OR REPLACE INTO secret_settings (key, value, updated_at) VALUES (?, ?, ?)',
      [key, value, now],
    );
  }

  deleteSecretSetting(key: string): void {
    this.query('DELETE FROM secret_settings WHERE key = ?', [key]);
  }
}
