"""Picker identity photo — a face photo (so a customer can visually confirm
the person who shows up is who they registered, not someone else) taken via
the device camera at signup or profile edit, optional for now (will be
required once the platform has enough volume to justify the extra signup
friction). Stored in Supabase Storage rather than local disk (unlike
product/home-content images), so it survives redeploys and is reviewable by
admin from anywhere. The license/ID is a plain typed license number, not an
uploaded image — no document-checking API involved."""

import os
import uuid

from .supabase_client import get_client

BUCKET = 'pickker-picker-docs'


def upload_picker_document(image_file, subdir, allowed_content_types=None, max_size_bytes=None):
    """subdir is 'photos' — kept as a parameter (rather than hardcoding) in
    case another document type is added later. Returns the public URL.

    allowed_content_types/max_size_bytes default to None (today's original
    behavior: no validation at all) so the two existing photo-upload call
    sites are unaffected — new call sites (e.g. fuel receipts, which also
    accept PDFs) opt into real checks by passing them. Raises ValueError
    with a plain message on rejection, for the calling view to surface."""
    content_type = getattr(image_file, 'content_type', None) or 'application/octet-stream'
    if allowed_content_types is not None and content_type not in allowed_content_types:
        raise ValueError(f'Unsupported file type: {content_type}')
    if max_size_bytes is not None and image_file.size > max_size_bytes:
        raise ValueError(f'File is too large (max {max_size_bytes // (1024 * 1024)}MB)')

    ext = os.path.splitext(image_file.name)[1] or '.jpg'
    path = f'{subdir}/{uuid.uuid4().hex}{ext}'
    client = get_client()
    client.storage.from_(BUCKET).upload(
        path, image_file.read(), file_options={'content-type': content_type},
    )
    return client.storage.from_(BUCKET).get_public_url(path)
