import Testing
import UIKit
@testable import 康康

struct FileVaultTests {

    private func makeIsolatedVault() throws -> FileVault {
        let temp = FileManager.default.temporaryDirectory
            .appendingPathComponent(UUID().uuidString, isDirectory: true)
        return try FileVault(rootURL: temp)
    }

    private func makeTestImage() -> UIImage {
        let size = CGSize(width: 16, height: 16)
        let renderer = UIGraphicsImageRenderer(size: size)
        return renderer.image { ctx in
            UIColor.red.setFill()
            ctx.fill(CGRect(origin: .zero, size: size))
        }
    }

    @Test func writeAndReadJPEGRoundtrip() throws {
        let vault = try makeIsolatedVault()
        defer { try? FileManager.default.removeItem(at: vault.rootURL) }
        let image = makeTestImage()

        let saved = try vault.writeJPEG(image, quality: 0.8)

        #expect(saved.bytes > 0)
        #expect(saved.relativePath.hasSuffix(".jpg"))

        let loaded = try vault.loadImage(relativePath: saved.relativePath)
        #expect(loaded.size != .zero)
    }

    @Test func removeMakesFileGone() throws {
        let vault = try makeIsolatedVault()
        defer { try? FileManager.default.removeItem(at: vault.rootURL) }
        let saved = try vault.writeJPEG(makeTestImage())

        try vault.remove(relativePath: saved.relativePath)

        #expect(throws: (any Error).self) {
            _ = try vault.loadImage(relativePath: saved.relativePath)
        }
    }

    @Test func wipeRemovesAllFiles() throws {
        let vault = try makeIsolatedVault()
        defer { try? FileManager.default.removeItem(at: vault.rootURL) }
        let a = try vault.writeJPEG(makeTestImage())
        let b = try vault.writeJPEG(makeTestImage())

        try vault.wipe()

        #expect(throws: (any Error).self) { _ = try vault.loadImage(relativePath: a.relativePath) }
        #expect(throws: (any Error).self) { _ = try vault.loadImage(relativePath: b.relativePath) }
    }
}
