import os

from django.core.exceptions import ValidationError

from .models import JobAttachment

IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp'}
DOCUMENT_EXTENSIONS = {'.pdf', '.doc', '.docx'}
ALLOWED_EXTENSIONS = IMAGE_EXTENSIONS | DOCUMENT_EXTENSIONS
MAX_ATTACHMENT_SIZE = 10 * 1024 * 1024  # 10 MB


def attachment_kind(filename):
    ext = os.path.splitext(filename.lower())[1]
    if ext in IMAGE_EXTENSIONS:
        return JobAttachment.Kind.IMAGE
    if ext in DOCUMENT_EXTENSIONS:
        return JobAttachment.Kind.PDF
    return None


def validate_attachment_file(uploaded_file):
    if not uploaded_file:
        return
    kind = attachment_kind(uploaded_file.name)
    if not kind:
        allowed = ', '.join(sorted(ALLOWED_EXTENSIONS))
        raise ValidationError(f'Unsupported file type. Allowed: {allowed}')
    if uploaded_file.size > MAX_ATTACHMENT_SIZE:
        raise ValidationError('Each file must be 10 MB or smaller.')


def save_job_attachments(job, files, *, start_order=0):
    """Create JobAttachment rows for uploaded files. Returns count saved."""
    created = 0
    order = start_order
    for uploaded_file in files:
        if not uploaded_file:
            continue
        validate_attachment_file(uploaded_file)
        kind = attachment_kind(uploaded_file.name)
        JobAttachment.objects.create(
            job=job,
            file=uploaded_file,
            kind=kind,
            title=os.path.splitext(uploaded_file.name)[0][:200],
            sort_order=order,
        )
        order += 1
        created += 1
    return created
