namespace Ikar.Server.Infrastructure.Storage;

public sealed record AttachmentContentInfo(string ContentType, bool IsImage, bool IsVideo);

public static class AttachmentContentInspector
{
    public static AttachmentContentInfo Inspect(IFormFile file)
    {
        Span<byte> header = stackalloc byte[16];
        using var stream = file.OpenReadStream();
        var read = stream.Read(header);
        var bytes = header[..read];

        if (StartsWith(bytes, [0xFF, 0xD8, 0xFF])) return new("image/jpeg", true, false);
        if (StartsWith(bytes, [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])) return new("image/png", true, false);
        if (StartsWith(bytes, "GIF87a"u8) || StartsWith(bytes, "GIF89a"u8)) return new("image/gif", true, false);
        if (StartsWith(bytes, "BM"u8)) return new("image/bmp", true, false);
        if (read >= 12 && StartsWith(bytes, "RIFF"u8) && bytes[8..12].SequenceEqual("WEBP"u8)) return new("image/webp", true, false);
        if (read >= 8 && bytes[4..8].SequenceEqual("ftyp"u8)) return new("video/mp4", false, true);
        if (StartsWith(bytes, [0x1A, 0x45, 0xDF, 0xA3])) return new("video/webm", false, true);
        if (StartsWith(bytes, "OggS"u8)) return new("audio/ogg", false, false);
        if (StartsWith(bytes, "%PDF-"u8)) return new("application/pdf", false, false);
        if (StartsWith(bytes, [0x50, 0x4B, 0x03, 0x04])) return new("application/zip", false, false);

        return new("application/octet-stream", false, false);
    }

    private static bool StartsWith(ReadOnlySpan<byte> bytes, ReadOnlySpan<byte> signature) =>
        bytes.Length >= signature.Length && bytes[..signature.Length].SequenceEqual(signature);
}
