import type { TaskStore, ServerCallContext } from '@a2a-js/sdk/server';
import type { Task } from '@a2a-js/sdk';
import type { Repository } from '../../db/repository.js';

/**
 * SQLite-backed TaskStore for the A2A SDK.
 *
 * Persists Task objects via Repository.saveA2aTask / loadA2aTask.
 * Executor (Task 6) convention: place Maestro linkage in task.metadata:
 *   - metadata.maestroJobId       → jobs.id (string)
 *   - metadata.maestroLocalTaskId → local_tasks.id (number)
 * Delegation convention (Task 2C-1):
 *   - metadata.a2aDelegationId  → a2a_tasks.delegation_id
 *   - metadata.a2aGrantId       → a2a_tasks.grant_id
 *   - metadata.a2aActingUserId  → a2a_tasks.acting_user_id
 */
export class SqliteA2aTaskStore implements TaskStore {
  constructor(private readonly repo: Repository) {}

  async save(task: Task, _context?: ServerCallContext): Promise<void> {
    this.repo.saveA2aTask({
      id: task.id,
      contextId: task.contextId ?? null,
      jobId: (task.metadata?.maestroJobId as string) ?? null,
      localTaskId: (task.metadata?.maestroLocalTaskId as number) ?? null,
      payload: task,
      delegationId: (task.metadata?.a2aDelegationId as string) ?? undefined,
      grantId: (task.metadata?.a2aGrantId as string) ?? undefined,
      actingUserId: (task.metadata?.a2aActingUserId as string) ?? undefined,
    });
  }

  async load(taskId: string, _context?: ServerCallContext): Promise<Task | undefined> {
    return this.repo.loadA2aTask(taskId)?.payload as Task | undefined;
  }
}
