-- v29 — SQL-side license capacity check (InstancesAllowed enforcement surface)

USE SovereignRepository;
GO

CREATE OR ALTER VIEW ctl.vw_LicenseCapacity AS
SELECT
  le.Edition,
  le.Tier,
  le.InstancesAllowed,
  le.ExpiresAt,
  le.IsActive,
  InstancesUsed = (SELECT COUNT(*) FROM ctl.Servers s WHERE s.IsActive = 1)
FROM ctl.LicenseEntitlements le
WHERE le.IsActive = 1;
GO

CREATE OR ALTER PROCEDURE ctl.usp_CheckInstanceCapacity
AS
BEGIN
  SET NOCOUNT ON;
  DECLARE @allowed INT, @used INT;
  SELECT TOP 1 @allowed = InstancesAllowed
  FROM ctl.LicenseEntitlements WHERE IsActive = 1 ORDER BY CreatedAt DESC;
  SELECT @used = COUNT(*) FROM ctl.Servers WHERE IsActive = 1;
  SELECT
    InstancesAllowed = ISNULL(@allowed, 0),
    InstancesUsed = ISNULL(@used, 0),
    CanRegister = CASE WHEN @allowed IS NULL THEN 0 WHEN @used < @allowed THEN 1 ELSE 0 END;
END;
GO
