package com.foxx.androidcast.ota;

/*********************************************************************
 * OtaBundleInstallerTest.java
 * Created at: Wed 20 May 2026 15:17:13 +0200
 * Updated at: Wed 20 May 2026 15:17:13 +0200 by Anton Afanasyeu <a.afanasieff@gmail.com>
 * Commit: 5d8e82d2e60a21fff3138d2a394ee4e8b4c6dcb8
 * class OtaBundleInstallerTest
 * Contributors:
 *    - Anton Afanasyeu <a.afanasieff@gmail.com> (1 commits, 61 lines)
 *    - Cursor Agent (project assistant)
 * Digest: SHA256	265506219a2e79ef3abfc2f82766222437b87f3d3fd6de82862628016250ea12
**********************************************************************/
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class OtaBundleInstallerTest {
    @org.junit.Rule
    public TemporaryFolder tmp = new TemporaryFolder();

    @Test
    public void unzipBundle_extractsPackageApk() throws Exception {
        File zip = tmp.newFile("test.otabundle.zip");
        byte[] apkBytes = "fake-apk".getBytes(StandardCharsets.UTF_8);
        try (ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(
                new FileOutputStream(zip)))) {
            writeStoredEntry(zos, OtaBundleInstaller.ENTRY_SIGN,
                    "{\"schema\":\"v0\",\"sha256\":\"deadbeef\"}");
            writeStoredEntry(zos, OtaBundleInstaller.ENTRY_PACKAGE, new String(apkBytes, StandardCharsets.UTF_8));
        }
        File dest = tmp.newFolder("extract");
        OtaBundleInstaller.unzipBundle(zip, dest);
        File apk = new File(dest, OtaBundleInstaller.ENTRY_PACKAGE);
        assertTrue(apk.isFile());
        assertEquals(apkBytes.length, apk.length());
    }

    private static void writeStoredEntry(ZipOutputStream zos, String name, String body)
            throws Exception {
        ZipEntry e = new ZipEntry(name);
        e.setMethod(ZipEntry.STORED);
        byte[] data = body.getBytes(StandardCharsets.UTF_8);
        e.setSize(data.length);
        e.setCompressedSize(data.length);
        e.setCrc(crc32(data));
        zos.putNextEntry(e);
        zos.write(data);
        zos.closeEntry();
    }

    private static long crc32(byte[] data) {
        java.util.zip.CRC32 crc = new java.util.zip.CRC32();
        crc.update(data);
        return crc.getValue();
    }
}
