package infra

import "testing"

func TestFileValidateType(t *testing.T) {
	allowed := []string{"image/png", "image/jpeg", "application/pdf", "image/webp"}

	t.Run("detecta JPEG por magic bytes", func(t *testing.T) {
		header := []byte{0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01}
		mime, ok := FileValidateType(header, allowed)
		if mime != "image/jpeg" || !ok {
			t.Fatalf("got (%q,%v), want (image/jpeg,true)", mime, ok)
		}
	})

	t.Run("detecta PNG por magic bytes", func(t *testing.T) {
		header := []byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D}
		mime, ok := FileValidateType(header, allowed)
		if mime != "image/png" || !ok {
			t.Fatalf("got (%q,%v), want (image/png,true)", mime, ok)
		}
	})

	t.Run("detecta PDF", func(t *testing.T) {
		header := []byte{0x25, 0x50, 0x44, 0x46, 0x2D, 0x31, 0x2E, 0x37}
		mime, ok := FileValidateType(header, allowed)
		if mime != "application/pdf" || !ok {
			t.Fatalf("got (%q,%v), want (application/pdf,true)", mime, ok)
		}
	})

	t.Run("detecta WebP con prefix RIFF y suffix WEBP", func(t *testing.T) {
		header := []byte{
			0x52, 0x49, 0x46, 0x46, // RIFF
			0xAA, 0xBB, 0xCC, 0xDD, // tamano (cualquier valor)
			0x57, 0x45, 0x42, 0x50, // WEBP
			0x56, 0x50, 0x38, 0x20,
		}
		mime, ok := FileValidateType(header, allowed)
		if mime != "image/webp" || !ok {
			t.Fatalf("got (%q,%v), want (image/webp,true)", mime, ok)
		}
	})

	t.Run("rechaza tipo no permitido", func(t *testing.T) {
		// PDF detectado, pero no en allowedTypes
		header := []byte{0x25, 0x50, 0x44, 0x46, 0x2D}
		mime, ok := FileValidateType(header, []string{"image/png"})
		if mime != "application/pdf" {
			t.Fatalf("got mime %q, want application/pdf", mime)
		}
		if ok {
			t.Fatalf("got ok=true, want false (PDF no en allowedTypes)")
		}
	})

	t.Run("tipo desconocido retorna vacio", func(t *testing.T) {
		header := []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}
		mime, ok := FileValidateType(header, allowed)
		if mime != "" || ok {
			t.Fatalf("got (%q,%v), want (\"\",false)", mime, ok)
		}
	})

	t.Run("header demasiado corto retorna vacio", func(t *testing.T) {
		header := []byte{0xFF}
		mime, ok := FileValidateType(header, allowed)
		if mime != "" || ok {
			t.Fatalf("got (%q,%v), want (\"\",false)", mime, ok)
		}
	})
}
