"use strict";

function validateDeploymentSource(event, registry) {
  const entry = registry && registry[event.repo];
  if (!entry) return "deployment_repository_not_registered";
  const policy = entry.deployment_policy;
  if (!policy) return "";
  if (policy.deployable === false) return "deployment_repository_not_deployable";

  const source = event.deployment_source;
  if (!source || typeof source !== "object") return "deployment_source_binding_required";
  const profile = (policy.profiles || []).find(candidate =>
    candidate.repository_id === source.repository_id
    && candidate.channel_id === source.channel_id
    && candidate.distribution === source.distribution
  );
  if (!profile) return "deployment_source_profile_not_registered";
  if (profile.state && profile.state !== "active") return "deployment_source_profile_inactive";
  if (profile.source_owner_id !== source.owner_id) return "deployment_source_owner_mismatch";
  if (!(profile.allowed_authorizers || []).includes(event.authorizer_id)) return "deployment_authorizer_not_allowed";
  if (!(profile.allowed_personas || []).includes(event.persona_id)) return "deployment_persona_not_allowed";
  if (!(profile.allowed_execution_runtimes || []).includes(event.execution_runtime_id)) return "deployment_execution_runtime_not_allowed";
  if (!(profile.allowed_targets || []).includes(event.target)) return "deployment_target_not_allowed";
  return "";
}

module.exports = { validateDeploymentSource };
