/**
 * Fleet schema validation — valid docs pass; missing productId / bad enum fail.
 */

import { describe, it, expect } from 'vitest';
import {
  FleetJobDocSchema,
  FleetRunDocSchema,
  FleetLeaseDocSchema,
  FleetFactoryDocSchema,
  FleetProfileDocSchema,
  FleetEventDocSchema,
  FleetArtifactDocSchema,
  SubmitJobSchema,
  PatchJobSchema,
  ClaimSchema,
  FLEET_STAGES,
  FLEET_PRIORITIES,
} from './types.js';

const now = '2026-05-30T00:00:00.000Z';

const validJob = {
  id: 'fjob_1',
  productId: 'lysnrai',
  stage: 'queued',
  idempotencyKey: 'task-1',
  contentHash: 'abc',
  bodyMd: '# task',
  manifestSnapshot: {
    priority: 'medium',
    capabilities: [],
    prefersEngine: [],
    allowedScope: [],
    deps: [],
  },
  priority: 'medium',
  priorityOrder: 2,
  capabilities: [],
  deps: [],
  kind: 'leaf',
  attempts: 0,
  leaseEpoch: 0,
  rev: 0,
  createdAt: now,
  updatedAt: now,
};

describe('FleetJobDocSchema', () => {
  it('accepts a valid job', () => {
    expect(FleetJobDocSchema.safeParse(validJob).success).toBe(true);
  });
  it('rejects a missing productId', () => {
    const { productId: _omit, ...bad } = validJob;
    expect(FleetJobDocSchema.safeParse(bad).success).toBe(false);
  });
  it('rejects an empty productId', () => {
    expect(FleetJobDocSchema.safeParse({ ...validJob, productId: '' }).success).toBe(false);
  });
  it('rejects an invalid stage enum', () => {
    expect(FleetJobDocSchema.safeParse({ ...validJob, stage: 'done' }).success).toBe(false);
  });
  it('rejects an invalid priority enum', () => {
    expect(FleetJobDocSchema.safeParse({ ...validJob, priority: 'urgent' }).success).toBe(false);
  });
});

describe('FleetRunDocSchema', () => {
  const validRun = {
    id: 'fjob_1:run:1',
    productId: 'lysnrai',
    jobId: 'fjob_1',
    attempt: 1,
    engine: 'devin',
    startedAt: now,
    insights: { tokensIn: 10, tokensOut: 5 },
  };
  it('accepts a valid run', () => {
    expect(FleetRunDocSchema.safeParse(validRun).success).toBe(true);
  });
  it('rejects missing productId', () => {
    const { productId: _o, ...bad } = validRun;
    expect(FleetRunDocSchema.safeParse(bad).success).toBe(false);
  });
  it('rejects attempt <= 0', () => {
    expect(FleetRunDocSchema.safeParse({ ...validRun, attempt: 0 }).success).toBe(false);
  });
});

describe('FleetLeaseDocSchema', () => {
  const validLease = {
    id: 'fjob_1',
    productId: 'lysnrai',
    jobId: 'fjob_1',
    leaseEpoch: 1,
    renewals: 0,
    status: 'held',
    rev: 0,
    updatedAt: now,
  };
  it('accepts a valid lease', () => {
    expect(FleetLeaseDocSchema.safeParse(validLease).success).toBe(true);
  });
  it('rejects an invalid status', () => {
    expect(FleetLeaseDocSchema.safeParse({ ...validLease, status: 'open' }).success).toBe(false);
  });
  it('rejects missing productId', () => {
    const { productId: _o, ...bad } = validLease;
    expect(FleetLeaseDocSchema.safeParse(bad).success).toBe(false);
  });
});

describe('FleetFactoryDocSchema', () => {
  const validFactory = {
    id: 'fac_1',
    productId: 'lysnrai',
    factoryId: 'fac_1',
    descriptor: { os: 'mac' },
    capabilities: ['os:mac'],
    health: 'ok',
    load: 0,
    seatLimit: 2,
    lastHeartbeatAt: now,
  };
  it('accepts a valid factory', () => {
    expect(FleetFactoryDocSchema.safeParse(validFactory).success).toBe(true);
  });
  it('rejects invalid health enum', () => {
    expect(FleetFactoryDocSchema.safeParse({ ...validFactory, health: 'sick' }).success).toBe(
      false
    );
  });
});

describe('FleetProfileDocSchema / FleetEventDocSchema / FleetArtifactDocSchema', () => {
  it('accepts a valid profile and rejects missing productId', () => {
    const valid = {
      id: 'prof_1',
      productId: 'lysnrai',
      name: 'backend',
      version: 1,
      snapshot: {},
      createdAt: now,
    };
    expect(FleetProfileDocSchema.safeParse(valid).success).toBe(true);
    const { productId: _o, ...bad } = valid;
    expect(FleetProfileDocSchema.safeParse(bad).success).toBe(false);
  });
  it('accepts a valid event and rejects missing type', () => {
    const valid = {
      id: 'fjob_1:evt:0',
      productId: 'lysnrai',
      jobId: 'fjob_1',
      seq: 0,
      type: 'submitted',
      at: now,
      data: {},
    };
    expect(FleetEventDocSchema.safeParse(valid).success).toBe(true);
    const { type: _t, ...bad } = valid;
    expect(FleetEventDocSchema.safeParse(bad).success).toBe(false);
  });
  it('accepts a valid artifact pointer and rejects missing blobKey', () => {
    const valid = {
      id: 'art_1',
      productId: 'lysnrai',
      jobId: 'fjob_1',
      kind: 'coverage',
      blobKey: 'fleet/lysnrai/fjob_1/art_1-coverage',
      contentType: 'application/json',
      sizeBytes: 1234,
      createdAt: now,
    };
    expect(FleetArtifactDocSchema.safeParse(valid).success).toBe(true);
    const { blobKey: _b, ...bad } = valid;
    expect(FleetArtifactDocSchema.safeParse(bad).success).toBe(false);
    // kind is a closed enum — an unknown kind is rejected
    expect(FleetArtifactDocSchema.safeParse({ ...valid, kind: 'bogus' }).success).toBe(false);
  });
});

describe('request schemas', () => {
  it('SubmitJobSchema applies defaults', () => {
    const parsed = SubmitJobSchema.safeParse({ idempotencyKey: 'k', bodyMd: '# do' });
    expect(parsed.success).toBe(true);
    if (parsed.success) {
      expect(parsed.data.priority).toBe('medium');
      expect(parsed.data.kind).toBe('leaf');
      expect(parsed.data.deps).toEqual([]);
    }
  });
  it('SubmitJobSchema rejects empty bodyMd / idempotencyKey', () => {
    expect(SubmitJobSchema.safeParse({ idempotencyKey: '', bodyMd: 'x' }).success).toBe(false);
    expect(SubmitJobSchema.safeParse({ idempotencyKey: 'k', bodyMd: '' }).success).toBe(false);
  });
  it('PatchJobSchema requires leaseEpoch', () => {
    expect(PatchJobSchema.safeParse({ stage: 'building' }).success).toBe(false);
    expect(PatchJobSchema.safeParse({ leaseEpoch: 1, stage: 'building' }).success).toBe(true);
  });
  it('ClaimSchema requires factoryId', () => {
    expect(ClaimSchema.safeParse({ capabilities: [] }).success).toBe(false);
    expect(ClaimSchema.safeParse({ factoryId: 'fac_1' }).success).toBe(true);
  });
});

describe('enum constants', () => {
  it('stages match the agent-queue lifecycle', () => {
    expect(FLEET_STAGES).toEqual([
      'draft',
      'queued',
      'blocked',
      'assigned',
      'building',
      'review',
      'testing',
      'shipped',
      'failed',
      'dead_letter',
    ]);
  });
  it('priorities', () => {
    expect(FLEET_PRIORITIES).toEqual(['critical', 'high', 'medium', 'low']);
  });
});
