/**
 * MIT License
 *
 * Copyright (C) 2026 Huawei Device Co., Ltd.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

// The download helper is mocked so getPixelMap/downloadFile tests can control
// the downloaded path (success / failure) without going through rcp.
jest.mock(
  '../../harmony/createThumbnail/src/main/ets/download/RequestDownload',
  () => {
    const instances: any[] = [];
    class MockRequestDownload {
      downloadFile = jest.fn();
      constructor(public context: any) {
        instances.push(this);
      }
    }
    return {
      __esModule: true,
      default: MockRequestDownload,
      __mockInstances: instances,
    };
  }
);

import { CreateThumbnailTurboModule } from '../../harmony/createThumbnail/src/main/ets/CreateThumbnailTurboModule';
import { __mockInstances } from '../../harmony/createThumbnail/src/main/ets/download/RequestDownload';
import { fileUtils } from '../../harmony/createThumbnail/src/main/ets/util/FileUtil';
import fsDefault, {
  __resetFsMock,
  __setFsExists,
  __setFsListing,
  __setFsStat,
  OpenMode,
} from '../mocks/ohos/fs';
import { getUriFromPath } from '../mocks/ohos/fileuri';
import imageDefault, {
  __imageState,
  __resetImageMock,
  __setCachePixelMap,
  createMockPixelMap,
} from '../mocks/ohos/image';
import mediaDefault, {
  __mediaState,
  __resetMediaMock,
  __setFrameResult,
  __setMetadata,
  AVImageQueryOptions,
} from '../mocks/ohos/media';

const FILES_DIR = '/data/app/files';
const CACHE_DIR = `${FILES_DIR}/thumbnails`;
const APP_CACHE_DIR = '/data/app/cache';
const UI_ABILITY_CONTEXT = { filesDir: FILES_DIR, cacheDir: APP_CACHE_DIR };
const CTX = { uiAbilityContext: UI_ABILITY_CONTEXT };
const UUID = '11111111-2222-3333-4444-555555555555';
const LOCAL_VIDEO_URL = 'file://media/videos/v.mp4';
const LOCAL_VIDEO_PATH = '/media/videos/v.mp4';
const REMOTE_VIDEO_URL = 'https://cdn.example.com/videos/v.mp4';

const DOWNLOADS = () => __mockInstances[__mockInstances.length - 1];

describe('CreateThumbnailTurboModule', () => {
  let tm: CreateThumbnailTurboModule;

  beforeEach(() => {
    __resetFsMock();
    __resetImageMock();
    __resetMediaMock();
    __mockInstances.length = 0;
    __setFsExists(CACHE_DIR, true);
    tm = new CreateThumbnailTurboModule(CTX as any);
  });

  afterEach(() => {
    jest.restoreAllMocks();
  });

  describe('constructor', () => {
    it('creates the RequestDownload helper with the UIAbilityContext', () => {
      expect(DOWNLOADS().context).toBe(UI_ABILITY_CONTEXT);
    });
  });

  describe('ensureCacheDir', () => {
    it('creates <filesDir>/thumbnails when it does not exist yet', () => {
      __setFsExists(CACHE_DIR, false);

      expect((tm as any).ensureCacheDir()).toBe(CACHE_DIR);
      expect(fsDefault.mkdirSync).toHaveBeenCalledWith(CACHE_DIR);
    });

    it('keeps an existing thumbnails directory untouched', () => {
      expect((tm as any).ensureCacheDir()).toBe(CACHE_DIR);
      expect(fsDefault.mkdirSync).not.toHaveBeenCalled();
    });
  });

  describe('checkCache', () => {
    it('skips the cache when cacheName is null, empty or undefined', async () => {
      await expect(
        (tm as any).checkCache(CACHE_DIR, null, 'jpeg')
      ).resolves.toBeNull();
      await expect(
        (tm as any).checkCache(CACHE_DIR, '', 'jpeg')
      ).resolves.toBeNull();
      await expect(
        (tm as any).checkCache(CACHE_DIR, undefined, 'jpeg')
      ).resolves.toBeNull();
      expect(imageDefault.createImageSource).not.toHaveBeenCalled();
    });

    it('skips the cache when the cached file does not exist', async () => {
      await expect(
        (tm as any).checkCache(CACHE_DIR, 'thumb', 'png')
      ).resolves.toBeNull();
      expect(fsDefault.accessSync).toHaveBeenCalledWith(
        `${CACHE_DIR}/thumb.png`
      );
      expect(imageDefault.createImageSource).not.toHaveBeenCalled();
    });

    it('decodes and returns the cached thumbnail on a hit', async () => {
      __setFsExists(`${CACHE_DIR}/thumb.png`, true);
      __setCachePixelMap(
        createMockPixelMap({ width: 120, height: 60, bytes: 600 })
      );

      const result = await (tm as any).checkCache(
        CACHE_DIR,
        'thumb',
        'png'
      );

      expect(imageDefault.createImageSource).toHaveBeenCalledWith(
        `${CACHE_DIR}/thumb.png`
      );
      expect(__imageState.sources[0].createPixelMap).toHaveBeenCalledWith({
        editable: true,
        pixelFormat: 3,
      });
      expect(result).toEqual({
        path: `file://${CACHE_DIR}/thumb.png`,
        size: 600,
        mime: 'image/png',
        width: 120,
        height: 60,
      });
    });
  });

  describe('prepareConfig', () => {
    it('fills every field with defaults for an empty config', () => {
      expect((tm as any).prepareConfig({}, CACHE_DIR, 'jpeg', '')).toEqual({
        filePath: '',
        dirSize: 100,
        timeStamp: 0,
        maxWidth: 512,
        maxHeight: 512,
        onlySyncedFrames: true,
        imagePath: `${CACHE_DIR}/thumb-${UUID}`,
      });
    });

    it('keeps the values provided by the caller', () => {
      const params = (tm as any).prepareConfig(
        {
          url: REMOTE_VIDEO_URL,
          dirSize: 5,
          timeStamp: 1234,
          maxWidth: 256,
          maxHeight: 128,
          onlySyncedFrames: false,
        },
        CACHE_DIR,
        'png',
        ''
      );

      expect(params.filePath).toBe(REMOTE_VIDEO_URL);
      expect(params.dirSize).toBe(5);
      expect(params.timeStamp).toBe(1234);
      expect(params.maxWidth).toBe(256);
      expect(params.maxHeight).toBe(128);
      expect(params.onlySyncedFrames).toBe(false);
      expect(params.imagePath).toBe(`${CACHE_DIR}/thumb-${UUID}`);
    });

    it('appends the format extension to a custom cacheName', () => {
      const params = (tm as any).prepareConfig(
        { cacheName: 'intro' },
        CACHE_DIR,
        'png',
        'intro'
      );

      expect(params.imagePath).toBe(`${CACHE_DIR}/intro.png`);
    });
  });

  describe('saveThumbnail', () => {
    it('packs png images with full quality and writes them to imagePath', async () => {
      const pixelMap = createMockPixelMap({ bytes: 100 });
      __setFsListing(CACHE_DIR, []);

      await (tm as any).saveThumbnail(
        pixelMap,
        `${CACHE_DIR}/t.png`,
        'png',
        CACHE_DIR,
        100
      );

      expect(__imageState.packers[0].packing).toHaveBeenCalledWith(pixelMap, {
        format: 'image/png',
        quality: 100,
      });
      expect(fsDefault.openSync).toHaveBeenCalledWith(
        `${CACHE_DIR}/t.png`,
        OpenMode.READ_WRITE | OpenMode.CREATE
      );
      expect(fsDefault.writeSync).toHaveBeenCalled();
      expect(fsDefault.closeSync).toHaveBeenCalled();
    });

    it('packs jpeg images with quality 90', async () => {
      __setFsListing(CACHE_DIR, []);

      await (tm as any).saveThumbnail(
        createMockPixelMap(),
        `${CACHE_DIR}/t.jpeg`,
        'jpeg',
        CACHE_DIR,
        100
      );

      expect(__imageState.packers[0].packing).toHaveBeenCalledWith(
        expect.anything(),
        { format: 'image/jpeg', quality: 90 }
      );
    });

    it('keeps the cache directory when the total size stays within the budget', async () => {
      const spy = jest.spyOn(fileUtils, 'cleanDir');
      __setFsListing(CACHE_DIR, ['old.png']);
      __setFsStat(`${CACHE_DIR}/old.png`, { size: 1024 });

      await (tm as any).saveThumbnail(
        createMockPixelMap({ bytes: 2048 }),
        `${CACHE_DIR}/t.png`,
        'png',
        CACHE_DIR,
        100
      );

      expect(spy).not.toHaveBeenCalled();
    });

    it('cleans the cache directory once the budget is exceeded', async () => {
      const spy = jest.spyOn(fileUtils, 'cleanDir');
      __setFsListing(CACHE_DIR, ['old.png']);
      __setFsStat(`${CACHE_DIR}/old.png`, { size: 1024 });

      await (tm as any).saveThumbnail(
        createMockPixelMap({ bytes: 2048 }),
        `${CACHE_DIR}/t.png`,
        'png',
        CACHE_DIR,
        0
      );

      expect(spy).toHaveBeenCalledWith(CACHE_DIR, 0);
    });
  });

  describe('parseThumbnail', () => {
    it('maps the pixel map and image info onto the thumbnail result', () => {
      const pixelMap = createMockPixelMap({
        width: 800,
        height: 600,
        bytes: 4800,
      });

      const thumbnail = tm.parseThumbnail(
        `${CACHE_DIR}/t.jpeg`,
        pixelMap as any,
        'jpeg',
        { size: { width: 800, height: 600 } } as any,
        2500,
        false,
        { auth: 'token' },
        20
      );

      expect(getUriFromPath).toHaveBeenCalledWith(`${CACHE_DIR}/t.jpeg`);
      expect(thumbnail).toEqual({
        path: `file://${CACHE_DIR}/t.jpeg`,
        size: 4800,
        mime: 'image/jpeg',
        width: 800,
        height: 600,
        timeStamp: 2500,
        onlySyncedFrames: false,
        headers: { auth: 'token' },
        dirSize: 20,
      });
    });

    it('leaves the optional fields unset when not provided', () => {
      const thumbnail = tm.parseThumbnail(
        '/x/y.png',
        createMockPixelMap() as any,
        'png',
        { size: { width: 1, height: 2 } } as any
      );

      expect(thumbnail.timeStamp).toBeUndefined();
      expect(thumbnail.onlySyncedFrames).toBeUndefined();
      expect(thumbnail.headers).toBeUndefined();
      expect(thumbnail.dirSize).toBeUndefined();
    });
  });

  describe('createThumbnail', () => {
    it('generates a thumbnail for a local video on a cache miss', async () => {
      __setMetadata({ videoWidth: '1280', videoHeight: '720' });
      __setFrameResult(
        createMockPixelMap({ width: 300, height: 169, bytes: 4096 })
      );
      __setFsListing(CACHE_DIR, []);

      const thumbnail = await tm.createThumbnail({
        url: LOCAL_VIDEO_URL,
        timeStamp: 500,
        format: 'png',
        dirSize: 10,
        headers: { auth: 'x' },
        maxWidth: 300,
        maxHeight: 300,
      } as any);

      expect(thumbnail).toEqual({
        path: `file://${CACHE_DIR}/thumb-${UUID}`,
        size: 4096,
        mime: 'image/png',
        width: 300,
        height: 169,
        timeStamp: 500,
        onlySyncedFrames: true,
        headers: { auth: 'x' },
        dirSize: 10,
      });
      const generator = __mediaState.generators[0];
      expect(generator.fetchFrameByTime).toHaveBeenCalledWith(
        500 * 1000,
        AVImageQueryOptions.AV_IMAGE_QUERY_CLOSEST_SYNC,
        { width: 300, height: 168.75 }
      );
    });

    it('returns the cached thumbnail without decoding the video', async () => {
      __setFsExists(`${CACHE_DIR}/hit.png`, true);
      __setCachePixelMap(
        createMockPixelMap({ width: 64, height: 32, bytes: 128 })
      );

      const thumbnail = await tm.createThumbnail({
        url: LOCAL_VIDEO_URL,
        cacheName: 'hit',
        format: 'png',
      } as any);

      expect(thumbnail.path).toBe(`file://${CACHE_DIR}/hit.png`);
      expect(mediaDefault.createAVImageGenerator).not.toHaveBeenCalled();
    });

    it('defaults the format to jpeg when the config omits it', async () => {
      __setFsListing(CACHE_DIR, []);

      const thumbnail = await tm.createThumbnail({
        url: LOCAL_VIDEO_URL,
      } as any);

      expect(thumbnail.mime).toBe('image/jpeg');
      expect(__imageState.packers[0].packing).toHaveBeenCalledWith(
        expect.anything(),
        { format: 'image/jpeg', quality: 90 }
      );
    });
  });

  describe('getPixelMap', () => {
    it('reads a file:// video through its file descriptor', async () => {
      __setFsStat(LOCAL_VIDEO_PATH, { size: 2048 });
      const marker = createMockPixelMap();
      __setFrameResult(marker);

      const pixelMap = await tm.getPixelMap(LOCAL_VIDEO_URL, 1000, 512, 512, true);

      expect(pixelMap).toBe(marker);
      const generator = __mediaState.generators[0];
      expect(generator.fdSrc).toMatchObject({ offset: 0, length: 2048 });
      expect(typeof generator.fdSrc.fd).toBe('number');
      expect(fsDefault.openSync).toHaveBeenCalledWith(
        LOCAL_VIDEO_PATH,
        OpenMode.READ_WRITE | OpenMode.READ_ONLY
      );
      expect(generator.fetchFrameByTime).toHaveBeenCalledWith(
        1000 * 1000,
        AVImageQueryOptions.AV_IMAGE_QUERY_CLOSEST_SYNC,
        expect.anything()
      );
    });

    it('requests the closest frame when onlySyncedFrames is false', async () => {
      __setFsStat(LOCAL_VIDEO_PATH, { size: 2048 });

      await tm.getPixelMap(LOCAL_VIDEO_URL, 0, 512, 512, false);

      expect(__mediaState.generators[0].fetchFrameByTime).toHaveBeenCalledWith(
        0,
        AVImageQueryOptions.AV_IMAGE_QUERY_CLOSEST,
        expect.anything()
      );
    });

    it('downloads a remote video before extracting the frame', async () => {
      const voidPath = `${APP_CACHE_DIR}/video/v.mp4`;
      __setFsStat(voidPath, { size: 4096 });
      DOWNLOADS().downloadFile.mockImplementation(
        (_folder: string, _url: string, cb: (p: string) => void) =>
          cb(voidPath)
      );
      const marker = createMockPixelMap();
      __setFrameResult(marker);

      const pixelMap = await tm.getPixelMap(REMOTE_VIDEO_URL, 0, 512, 512, true);

      expect(DOWNLOADS().downloadFile).toHaveBeenCalledWith(
        'video',
        REMOTE_VIDEO_URL,
        expect.any(Function)
      );
      expect(fsDefault.openSync).toHaveBeenCalledWith(
        voidPath,
        expect.any(Number)
      );
      expect(pixelMap).toBe(marker);
    });

    it('rejects with "download fail" when the download resolves empty', async () => {
      DOWNLOADS().downloadFile.mockImplementation(
        (_folder: string, _url: string, cb: (p: string) => void) => cb(null)
      );

      await expect(
        tm.getPixelMap(REMOTE_VIDEO_URL, 0, 512, 512, true)
      ).rejects.toBe('download fail');
      expect(__mediaState.generators[0].release).toHaveBeenCalled();
    });

    it('rejects for an unsupported url protocol', async () => {
      await expect(
        tm.getPixelMap('ftp://cdn.example.com/v.mp4', 0, 512, 512, true)
      ).rejects.toBe('Unsupported URL protocol');
      expect(__mediaState.generators[0].release).toHaveBeenCalled();
    });

    it('rejects when no frame could be extracted', async () => {
      __setFsStat(LOCAL_VIDEO_PATH, { size: 2048 });
      __setFrameResult(null);

      await expect(
        tm.getPixelMap(LOCAL_VIDEO_URL, 0, 512, 512, true)
      ).rejects.toBe("File doesn't exist or not supported");
      expect(__mediaState.generators[0].release).toHaveBeenCalled();
    });
  });

  describe('calcThumbnailSize', () => {
    it('scales a landscape video down to the width limit', async () => {
      __setMetadata({ videoWidth: '1920', videoHeight: '1080' });
      const fdSrc = { fd: 1, offset: 0, length: 10 };

      const param = await (tm as any).calcThumbnailSize(fdSrc, 512, 512);

      expect(param.width).toBeCloseTo(512, 5);
      expect(param.height).toBeCloseTo(288, 5);
      const extractor = __mediaState.extractors[0];
      expect(extractor.fdSrc).toEqual(fdSrc);
      expect(extractor.release).toHaveBeenCalled();
    });

    it('keeps a small video at its original size', async () => {
      __setMetadata({ videoWidth: '400', videoHeight: '300' });

      const param = await (tm as any).calcThumbnailSize(
        { fd: 1, offset: 0, length: 10 },
        512,
        512
      );

      expect(param).toEqual({ width: 400, height: 300 });
    });

    it('uses the height ratio for a portrait video', async () => {
      __setMetadata({ videoWidth: '1080', videoHeight: '1920' });

      const param = await (tm as any).calcThumbnailSize(
        { fd: 1, offset: 0, length: 10 },
        512,
        512
      );

      expect(param.width).toBeCloseTo(288, 5);
      expect(param.height).toBeCloseTo(512, 5);
    });

    it('parses metadata dimensions provided as strings', async () => {
      __setMetadata({ videoWidth: '640', videoHeight: '360' });

      const param = await (tm as any).calcThumbnailSize(
        { fd: 1, offset: 0, length: 10 },
        640,
        360
      );

      expect(param).toEqual({ width: 640, height: 360 });
    });
  });

  describe('parseFdSrc', () => {
    it('builds an AVFileDescriptor from the opened file', () => {
      __setFsStat(LOCAL_VIDEO_PATH, { size: 4096 });

      const fd = (tm as any).parseFdSrc(LOCAL_VIDEO_PATH);

      expect(fd).toMatchObject({ offset: 0, length: 4096 });
      expect(typeof fd.fd).toBe('number');
      expect(fsDefault.openSync).toHaveBeenCalledWith(
        LOCAL_VIDEO_PATH,
        OpenMode.READ_WRITE | OpenMode.READ_ONLY
      );
    });
  });

  describe('downloadFile', () => {
    it('resolves with the path reported by RequestDownload', async () => {
      const voidPath = `${APP_CACHE_DIR}/video/v.mp4`;
      DOWNLOADS().downloadFile.mockImplementation(
        (_folder: string, _url: string, cb: (p: string) => void) =>
          cb(voidPath)
      );

      await expect(tm.downloadFile(REMOTE_VIDEO_URL)).resolves.toBe(voidPath);
      expect(DOWNLOADS().downloadFile).toHaveBeenCalledWith(
        'video',
        REMOTE_VIDEO_URL,
        expect.any(Function)
      );
    });
  });
});