export type House = { id: string; name: string };
export interface SqlPort {
  exec(sql: string): Promise<void>;
  run(sql: string, ...values: (string | number)[]): Promise<void>;
  all<T>(sql: string, ...values: (string | number)[]): Promise<T[]>;
}
export class Repository {
  constructor(private db: SqlPort) {}
  async migrate() {
    await this.db.exec('PRAGMA foreign_keys=ON');
    const rows = await this.db.all<{ user_version: number }>('PRAGMA user_version');
    if (rows[0].user_version > 1) throw new Error('Database is newer than this app');
    await this.db.exec(`BEGIN IMMEDIATE;
      CREATE TABLE IF NOT EXISTS houses(id TEXT PRIMARY KEY,name TEXT NOT NULL);
      PRAGMA user_version=1;
      COMMIT;`);
  }
  async save(house: House) {
    await this.db.run('INSERT INTO houses(id,name) VALUES (?,?)', house.id, house.name);
  }
  all() { return this.db.all<House>('SELECT id,name FROM houses ORDER BY name,id'); }
}
export class HouseService {
  constructor(private repository: Repository, private id: () => string) {}
  async create(input: string) {
    const name = input.trim();
    if (!name) throw new Error('Name required');
    await this.repository.save({ id: this.id(), name });
  }
}
