using System.Reflection;
using JobTrackerApi.Controllers;
using JobTrackerApi.Data;
using JobTrackerApi.Models;
using JobTrackerApi.Services;
using JobTrackerApi.Tests.TestSupport;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging.Abstractions;
using Xunit;

namespace JobTrackerApi.Tests;

public sealed class BackupControllerTests
{
    [Fact]
    public void Backup_controller_requires_local_authorization()
    {
        var attribute = typeof(BackupController).GetCustomAttribute<AuthorizeAttribute>();
        Assert.NotNull(attribute);
        Assert.Equal("local", attribute!.AuthenticationSchemes);
    }

    [Fact]
    public void Export_controller_requires_local_authorization()
    {
        var attribute = typeof(ExportController).GetCustomAttribute<AuthorizeAttribute>();
        Assert.NotNull(attribute);
        Assert.Equal("local", attribute!.AuthenticationSchemes);
    }

    [Fact]
    public async Task Encrypted_returns_file_payload_on_non_windows_platforms_too()
    {
        await using var db = CreateDb();
        db.Companies.Add(new Company { Name = "Acme", OwnerUserId = "user-1" });
        db.JobApplications.Add(new JobApplication { JobTitle = "Backend Developer", OwnerUserId = "user-1" });
        await db.SaveChangesAsync();

        var provider = DataProtectionProvider.Create(new DirectoryInfo(Path.Combine(Path.GetTempPath(), $"jobtracker-tests-{Guid.NewGuid():N}")));
        var controller = new BackupController(db, new NullLogger<BackupController>(), provider);

        var result = await controller.Encrypted(CancellationToken.None);

        var file = Assert.IsType<FileContentResult>(result);
        Assert.Equal("application/octet-stream", file.ContentType);
        Assert.EndsWith(".jtbackup", file.FileDownloadName);
        Assert.NotEmpty(file.FileContents);
    }

    private static JobTrackerContext CreateDb()
    {
        return TestHostFactory.CreateInMemoryDb();
    }
}
