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

const DEFAULT_ORG_ID = 'personal-org';

export function getMinesProjectForOrg(projectId, orgId = DEFAULT_ORG_ID) {
  if (!projectId) return null;
  const expectedOrgId = orgId || DEFAULT_ORG_ID;
  return getDb().prepare(`
    SELECT mp.*, COALESCE(p.org_id, ?) AS effective_org_id
    FROM mines_projects mp
    LEFT JOIN projects p ON p.id = mp.os_project_id
    WHERE mp.id = ?
      AND COALESCE(p.org_id, ?) = ?
    LIMIT 1
  `).get(DEFAULT_ORG_ID, projectId, DEFAULT_ORG_ID, expectedOrgId) || null;
}

export function assertMinesProjectForOrg(projectId, orgId = DEFAULT_ORG_ID) {
  const project = getMinesProjectForOrg(projectId, orgId);
  if (!project) return { ok: false, error: 'project_not_found_or_forbidden' };
  return { ok: true, project };
}
