from minio import Minio
from django.conf import settings
from datetime import datetime, timedelta
from rest_framework.response import Response
from rest_framework import status
import boto3
from botocore.client import Config

client = Minio(
    settings.MINIO_ENDPOINT,
    access_key=settings.MINIO_ACCESS_KEY,
    secret_key=settings.MINIO_SECRET_KEY,
    secure=settings.MINIO_SECURE
)


def upload_damage_photo(photo_file, depot_id, content_type):
    try:
        s3_client = boto3.client('s3',
            endpoint_url=f'http://{settings.MINIO_ENDPOINT}',
            aws_access_key_id=settings.MINIO_ACCESS_KEY,
            aws_secret_access_key=settings.MINIO_SECRET_KEY,
            config=Config(signature_version='s3v4'),
            region_name='us-east-1'
        )

        # Use the full filename as the key, which includes the depot_id folder
        s3_client.upload_fileobj(
            photo_file,
            settings.MINIO_BUCKET_NAME,
            photo_file.name,
            ExtraArgs={'ContentType': content_type}
        )

        # Generate a presigned URL for the uploaded object
        url = s3_client.generate_presigned_url('get_object',
            Params={
                'Bucket': settings.MINIO_BUCKET_NAME,
                'Key': photo_file.name
            },
            ExpiresIn=3600
        )

        return url

    except Exception as e:
        print(f"Error uploading to MinIO: {str(e)}")
        raise


def get_damages(depot_id):
    try:
        objects = client.list_objects(
            settings.MINIO_BUCKET_NAME,
            prefix=f"{depot_id}/"
        )

        damages = []
        for obj in objects:
            url = client.presigned_get_object(
                settings.MINIO_BUCKET_NAME,
                obj.object_name,
                expires=timedelta(days=7)
            )
            damages.append({
                "url": url,
                "filename": obj.object_name.split('/')[-1]
            })

        return Response(damages, status=status.HTTP_200_OK)
    except Exception as e:
        print(f"Error listing objects from MinIO: {str(e)}")
        return Response([], status=status.HTTP_500_INTERNAL_SERVER_ERROR)