import { DateTimeColumn, WithTimestamps } from '@n8n/db';
import { Column, Entity, JoinColumn, ManyToOne, PrimaryColumn, type Relation } from '@n8n/typeorm';

import { Agent } from './agent.entity';

/** Distributed lock for a scheduled task run, shared by all main instances. */
@Entity({ name: 'agent_task_run_lock' })
export class AgentTaskRunLock extends WithTimestamps {
	@PrimaryColumn({
		type: 'varchar',
		length: 36,
		comment: 'Published agent whose scheduled task run is locked',
	})
	agentId: string;

	@ManyToOne(() => Agent, { onDelete: 'CASCADE' })
	@JoinColumn({ name: 'agentId' })
	agent: Relation<Agent>;

	@PrimaryColumn({
		type: 'varchar',
		length: 32,
		comment: 'Published task ID whose scheduled run is locked',
	})
	taskId: string;

	@Column({
		type: 'uuid',
		comment: 'Ephemeral lock owner token generated by the running main',
	})
	holderId: string;

	@DateTimeColumn({ comment: 'Time after which another main can claim this task run lock' })
	heldUntil: Date;
}
