/**
 * Projects Repository
 *
 * CRUD operations for projects.
 *
 * @module persistence/repositories/projects
 */
import { randomUUID } from "crypto";
import { basename } from "path";
export class ProjectsRepository {
    db;
    constructor(db) {
        this.db = db;
    }
    create(path, name) {
        const id = randomUUID();
        const projectName = name || basename(path);
        const createdAt = new Date().toISOString();
        this.db
            .prepare(`INSERT INTO projects (id, path, name, created_at)
         VALUES (?, ?, ?, ?)`)
            .run(id, path, projectName, createdAt);
        return { id, path, name: projectName, createdAt };
    }
    findById(id) {
        const row = this.db
            .prepare("SELECT * FROM projects WHERE id = ?")
            .get(id);
        return row ? this.mapRow(row) : undefined;
    }
    findByPath(path) {
        const row = this.db
            .prepare("SELECT * FROM projects WHERE path = ?")
            .get(path);
        return row ? this.mapRow(row) : undefined;
    }
    findOrCreate(path, name) {
        const existing = this.findByPath(path);
        if (existing)
            return existing;
        return this.create(path, name);
    }
    list() {
        const rows = this.db
            .prepare("SELECT * FROM projects ORDER BY last_scan_at DESC NULLS LAST, created_at DESC")
            .all();
        return rows.map((r) => this.mapRow(r));
    }
    updateLastScan(id) {
        this.db
            .prepare("UPDATE projects SET last_scan_at = datetime('now') WHERE id = ?")
            .run(id);
    }
    delete(id) {
        const result = this.db
            .prepare("DELETE FROM projects WHERE id = ?")
            .run(id);
        return result.changes > 0;
    }
    mapRow(row) {
        return {
            id: row.id,
            path: row.path,
            name: row.name,
            createdAt: row.created_at,
            lastScanAt: row.last_scan_at || undefined,
            metadata: row.metadata ? JSON.parse(row.metadata) : undefined,
        };
    }
}
//# sourceMappingURL=projects.js.map