import { describe, it, expect } from 'vitest';
import { DeleteObjectCommand, GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3';
import { S3Storage, s3ConfigFromEnv, type S3Config, type S3Like } from './s3.storage';

const CFG: S3Config = { endpoint: 'https://minio.test', region: 'us-east-1', bucket: 'iios', accessKeyId: 'k', secretAccessKey: 's', forcePathStyle: true };

/** A recording stub S3 client; GetObject returns whatever `store[key]` holds (or a NoSuchKey error). */
function stub(store: Record<string, { body: Buffer; mime: string }> = {}) {
  const calls: unknown[] = [];
  const client: S3Like = {
    async send(command: unknown) {
      calls.push(command);
      if (command instanceof PutObjectCommand) { store[command.input.Key!] = { body: command.input.Body as Buffer, mime: command.input.ContentType ?? '' }; return {}; }
      if (command instanceof DeleteObjectCommand) { delete store[command.input.Key!]; return {}; }
      if (command instanceof GetObjectCommand) {
        const hit = store[command.input.Key!];
        if (!hit) throw Object.assign(new Error('missing'), { name: 'NoSuchKey' });
        return { Body: { transformToByteArray: async () => new Uint8Array(hit.body) }, ContentType: hit.mime };
      }
      return {};
    },
  };
  return { client, calls, store };
}

describe('s3ConfigFromEnv', () => {
  it('builds config from env (path-style default true for MinIO)', () => {
    const cfg = s3ConfigFromEnv({ IIOS_S3_ENDPOINT: 'https://minio.x', IIOS_S3_BUCKET: 'b', IIOS_S3_ACCESS_KEY: 'k', IIOS_S3_SECRET_KEY: 's' } as NodeJS.ProcessEnv);
    expect(cfg).toMatchObject({ endpoint: 'https://minio.x', bucket: 'b', region: 'us-east-1', forcePathStyle: true });
  });
  it('returns null when bucket/keys are missing', () => {
    expect(s3ConfigFromEnv({ IIOS_S3_ENDPOINT: 'https://minio.x' } as NodeJS.ProcessEnv)).toBeNull();
  });
});

describe('S3Storage (StoragePort over S3/MinIO)', () => {
  it('put stores the object and returns size + sha256', async () => {
    const s = stub();
    const store = new S3Storage(CFG, s.client);
    const res = await store.put('scope/obj1', Buffer.from('hello'), 'text/plain');
    expect(res.sizeBytes).toBe(5);
    expect(res.checksumSha256).toMatch(/^[a-f0-9]{64}$/);
    const put = s.calls[0] as PutObjectCommand;
    expect(put.input).toMatchObject({ Bucket: 'iios', Key: 'scope/obj1', ContentType: 'text/plain' });
  });

  it('get round-trips the bytes + mime', async () => {
    const s = stub();
    const store = new S3Storage(CFG, s.client);
    await store.put('scope/obj2', Buffer.from('PDFDATA'), 'application/pdf');
    const got = await store.get('scope/obj2');
    expect(got).toEqual({ data: Buffer.from('PDFDATA'), mime: 'application/pdf', sizeBytes: 7 });
  });

  it('get returns null for a missing key (NoSuchKey → null, not throw)', async () => {
    const store = new S3Storage(CFG, stub().client);
    expect(await store.get('nope')).toBeNull();
  });

  it('remove issues a DeleteObject', async () => {
    const s = stub({ 'k': { body: Buffer.from('x'), mime: 't' } });
    await new S3Storage(CFG, s.client).remove('k');
    expect(s.calls.some((c) => c instanceof DeleteObjectCommand)).toBe(true);
    expect(s.store['k']).toBeUndefined();
  });
});
