import datetime

import requests
from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase

from vbv_lernwelt.core.models import User
from vbv_lernwelt.files.integrations import s3_get_client
from vbv_lernwelt.files.models import UploadFile


class UploadFileIntegrationTest(TestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.s3_client = s3_get_client()

    def setUp(self):
        self.user = User.objects.create(username="testuser")
        # Creating a dummy file for upload
        self.dummy_file = SimpleUploadedFile(
            "testfile.txt", b"these are the file contents!"
        )
        self.upload_file = UploadFile.objects.create(
            original_file_name="testfile.txt",
            file_name="testfile123.txt",
            file_type="text/plain",
            uploaded_by=self.user,
            file=self.dummy_file,
        )

    def tearDown(self):
        self.upload_file.delete_file()

    def test_upload_to_s3(self):
        # Verify if file is uploaded to S3
        response = self.s3_client.get_object(
            Bucket=settings.AWS_STORAGE_BUCKET_NAME, Key=str(self.upload_file.file)
        )
        self.assertEqual(response["Body"].read(), b"these are the file contents!")

    def test_url_property(self):
        self.upload_file.upload_finished_at = datetime.datetime.now()
        self.upload_file.save()
        url = self.upload_file.url
        response = requests.get(url)
        # Assert that the URL is a valid presigned S3 URL and accessible
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, b"these are the file contents!")

    def test_delete_file_method(self):
        file_path = str(self.upload_file.file)
        self.upload_file.delete_file()
        # Assert that the file is deleted from S3
        with self.assertRaises(self.s3_client.exceptions.NoSuchKey):
            self.s3_client.get_object(
                Bucket=settings.AWS_STORAGE_BUCKET_NAME, Key=file_path
            )
