"""BAN YARO — Gasthund-Zugang (Sitter-Subscriptions)"""

from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from database import db
from auth import get_current_user

router = APIRouter()


class AccessCreate(BaseModel):
    dog_id:      int
    sitter_id:   int
    valid_until: str  # 'YYYY-MM-DD'


@router.post("", status_code=201)
async def grant_access(data: AccessCreate, user=Depends(get_current_user)):
    """Besitzer gewährt Sitter-Zugang zu seinem Hund."""
    with db() as conn:
        dog = conn.execute("SELECT id, user_id FROM dogs WHERE id=?", (data.dog_id,)).fetchone()
        if not dog or dog["user_id"] != user["id"]:
            raise HTTPException(403, "Nicht dein Hund.")
        conn.execute("""
            INSERT INTO sitting_subscriptions (dog_id, owner_id, sitter_id, valid_until)
            VALUES (?, ?, ?, ?)
            ON CONFLICT(dog_id, sitter_id) DO UPDATE SET valid_until=excluded.valid_until
        """, (data.dog_id, user["id"], data.sitter_id, data.valid_until))
    return {"ok": True}


@router.delete("/{sub_id}")
async def revoke_access(sub_id: int, user=Depends(get_current_user)):
    """Besitzer widerruft Zugang (oder Sitter meldet sich selbst ab)."""
    with db() as conn:
        row = conn.execute("SELECT * FROM sitting_subscriptions WHERE id=?", (sub_id,)).fetchone()
        if not row:
            raise HTTPException(404, "Nicht gefunden.")
        if row["owner_id"] != user["id"] and row["sitter_id"] != user["id"]:
            raise HTTPException(403, "Kein Zugriff.")
        conn.execute("DELETE FROM sitting_subscriptions WHERE id=?", (sub_id,))
    return {"ok": True}


@router.get("/my")
async def my_subscriptions(user=Depends(get_current_user)):
    """Gibt alle aktiven Gasthunde zurück (als Sitter oder Besitzer)."""
    with db() as conn:
        rows = conn.execute("""
            SELECT ss.id, ss.dog_id, ss.valid_until,
                   d.name AS dog_name, d.foto_url, d.rasse,
                   d.foto_zoom, d.foto_offset_x, d.foto_offset_y,
                   u.name AS owner_name
            FROM sitting_subscriptions ss
            JOIN dogs  d ON d.id  = ss.dog_id
            JOIN users u ON u.id  = ss.owner_id
            WHERE ss.sitter_id = ?
              AND ss.valid_until >= date('now')
        """, (user["id"],)).fetchall()
        granted = conn.execute("""
            SELECT ss.id, ss.dog_id, ss.valid_until,
                   d.name AS dog_name,
                   u.name AS sitter_name
            FROM sitting_subscriptions ss
            JOIN dogs  d ON d.id  = ss.dog_id
            JOIN users u ON u.id  = ss.sitter_id
            WHERE ss.owner_id = ? AND ss.valid_until >= date('now')
        """, (user["id"],)).fetchall()
    return {
        "as_sitter":  [dict(r) for r in rows],
        "as_owner":   [dict(r) for r in granted],
    }
