import { Injectable } from '@nestjs/common';
import { DatabaseService } from '../../../infrastructure/database/database.service';
import { EntitlementProjectionService } from '../application/entitlement-projection.service';
@Injectable()
export class SubscriptionLifecycleWorker {
constructor(
private readonly database:DatabaseService,
private readonly entitlements:EntitlementProjectionService,
) {}
async run() {
const trial=await this.database.query<any>(
`update organization_subscriptions
set status='expired',updated_at=now(),version=version+1
where status='trialing' and trial_ends_at is not null and trial_ends_at<=now()
returning organization_id`,
);
const grace=await this.database.query<any>(
`update organization_subscriptions
set status='suspended',updated_at=now(),version=version+1
where status in ('past_due','grace_period')
and grace_ends_at is not null and grace_ends_at<=now()
returning organization_id`,
);
const overrideOrgs=await this.database.query<any>(
`update entitlement_overrides
set revoked_at=now()
where revoked_at is null and ends_at is not null and ends_at<=now()
returning organization_id`,
);
const orgs=new Set<string>([
...trial.map((x:any)=>x.organization_id),
...grace.map((x:any)=>x.organization_id),
...overrideOrgs.map((x:any)=>x.organization_id),
]);
for(const org of orgs) await this.entitlements.rebuild(org);
return {trialExpired:trial.length,suspended:grace.length,overridesExpired:overrideOrgs.length};
}
}
