"""
The wire shape of a capture — snake_case, exactly as
`features/quick-capture/data/api.js` spells it.

Two fields carry the reasoning:

- **`triaged_to` IS THE PAGE ID AND `triaged_to_name` IS DERIVED FROM IT.**
  `fromWire` builds `{pageId, pageName}` out of the pair, because the inbox has
  to be able to say WHERE a capture went and rows are not fetched per page
  here. The name is read-only and comes off the joined row; the view selects it
  with the capture so a full inbox is two queries rather than one per triaged
  card.
- **`user` IS NOT ON THE WIRE AT ALL.** It is set from the request in the view.
  A writable owner field on a list that is scoped by owner is the one way to
  write into somebody else's inbox.

There is no `page` field, no `?page=` and no `bulk` — see the model. This is
the single global inbox, and it is the only endpoint in `lifey_api` shaped that
way.
"""

from rest_framework import serializers

from ..models import Capture, Page


class CaptureSerializer(serializers.ModelSerializer):
    id = serializers.CharField(read_only=True)
    triaged_to = serializers.PrimaryKeyRelatedField(
        queryset=Page.objects.none(), allow_null=True, required=False
    )
    # `source='triaged_to.name'` rather than a method field: it reads straight
    # off the row the view already selected, and `default=None` is what keeps a
    # capture still in the inbox from raising on the missing attribute.
    triaged_to_name = serializers.CharField(
        source='triaged_to.name', read_only=True, default=None
    )

    class Meta:
        model = Capture
        fields = [
            'id',
            'title',
            'body',
            'pinned',
            'triaged_to',
            'triaged_to_name',
            'is_sample',
            'created_at',
        ]
        read_only_fields = []

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        request = self.context.get('request')
        if request is not None and request.user.is_authenticated:
            # Owner-scoped like every other page reference in the app: a
            # capture cannot be filed into a page the caller does not own.
            self.fields['triaged_to'].queryset = Page.objects.filter(
                space__user=request.user
            )
