import uuid
from datetime import datetime, time, timedelta, timezone

import pytest

from app.core import security
from app.models.user import User, UserRole
from app.services import branch_hours as branch_hours_service
from app.utils.phone import normalize_ethiopian_phone

SUPPLIER_PHONE = "0962000001"
SUPPLIER2_PHONE = "0962000002"
ADMIN_PHONE = "0962000003"
CUSTOMER_PHONE = "0962000004"
SEED_PIN = "111111"

# Covers the whole day, regardless of when the test suite actually runs.
ALL_DAY_HOURS = {"opens_at": "00:00:00", "closes_at": "23:59:59"}


def _addis_weekday_now() -> int:
    """Mirrors app.utils.time.addis_local_weekday so working_days tests
    are deterministic regardless of when the suite actually runs."""
    return (datetime.now(timezone.utc) + timedelta(hours=3)).weekday()


def _seed_user(db_session, phone, name, role, pin=SEED_PIN, email=None):
    normalized = normalize_ethiopian_phone(phone)
    user = User(
        phone=normalized,
        name=name,
        email=email or f"{normalized.lstrip('+')}@example.com",
        role=role.value,
        pin_hash=security.hash_pin(pin),
        is_phone_verified=True,
        is_email_verified=True,
    )
    db_session.add(user)
    db_session.commit()
    db_session.refresh(user)
    return user


def _login(client, phone, pin=SEED_PIN) -> str:
    resp = client.post("/api/v1/auth/login", json={"identifier": phone, "pin": pin})
    assert resp.status_code == 200, resp.text
    return resp.json()["access_token"]


def _auth_headers(token: str) -> dict:
    return {"Authorization": f"Bearer {token}"}


@pytest.fixture()
def supplier(db_session):
    return _seed_user(db_session, SUPPLIER_PHONE, "A Supplier", UserRole.SUPPLIER)


@pytest.fixture()
def supplier_token(client, supplier):
    return _login(client, SUPPLIER_PHONE)


@pytest.fixture()
def supplier2_token(client, db_session):
    _seed_user(db_session, SUPPLIER2_PHONE, "Another Supplier", UserRole.SUPPLIER)
    return _login(client, SUPPLIER2_PHONE)


@pytest.fixture()
def admin_token(client, db_session):
    _seed_user(db_session, ADMIN_PHONE, "An Admin", UserRole.ADMIN)
    return _login(client, ADMIN_PHONE)


@pytest.fixture()
def customer_token(client, db_session):
    _seed_user(db_session, CUSTOMER_PHONE, "A Customer", UserRole.CUSTOMER)
    return _login(client, CUSTOMER_PHONE)


@pytest.fixture()
def branch_and_item(client, supplier_token, admin_token):
    merchant = client.post(
        "/api/v1/merchants",
        json={"name": "Wow Burger"},
        headers=_auth_headers(supplier_token),
    ).json()
    branch = client.post(
        f"/api/v1/merchants/{merchant['id']}/branches",
        json={
            "name": "Bole Branch",
            "address": "Bole, Addis Ababa",
            "latitude": 9.005,
            "longitude": 38.763,
            "phone": "0911223344",
        },
        headers=_auth_headers(supplier_token),
    ).json()
    client.patch(
        f"/api/v1/branches/{branch['id']}/approve",
        json={"approval_status": "approved"},
        headers=_auth_headers(admin_token),
    )
    category = client.post(
        f"/api/v1/branches/{branch['id']}/categories",
        json={"name": "Mains"},
        headers=_auth_headers(supplier_token),
    ).json()
    item = client.post(
        f"/api/v1/branches/{branch['id']}/categories/{category['id']}/items",
        json={"name": "Beef Burger", "price": "150.00"},
        headers=_auth_headers(supplier_token),
    ).json()
    return branch, item


# --- is_branch_open() unit-level: overnight window, working_days -------


class _FakeBranch:
    def __init__(
        self, is_active=True, opens_at=None, closes_at=None, working_days=None
    ):
        self.is_active = is_active
        self.opens_at = opens_at
        self.closes_at = closes_at
        self.working_days = working_days if working_days is not None else list(range(7))


def _mock_now(monkeypatch, local_time: time, weekday: int):
    """branch_hours.utcnow is looked up by name from the module it was
    imported into, so patching it there (not on app.utils.time) is
    what actually takes effect. Finds the next date landing on the
    given weekday relative to right now, rather than hardcoding a
    specific calendar date, so this doesn't depend on knowing what day
    of the week any particular date actually fell on."""
    now_local = datetime.now(timezone.utc) + timedelta(hours=3)
    days_ahead = (weekday - now_local.weekday()) % 7
    local_date = (now_local + timedelta(days=days_ahead)).date()
    utc_time = datetime.combine(local_date, local_time) - timedelta(hours=3)
    monkeypatch.setattr(branch_hours_service, "utcnow", lambda: utc_time)


def test_is_branch_open_inactive_branch_always_closed():
    branch = _FakeBranch(is_active=False)
    assert branch_hours_service.is_branch_open(branch) is False


def test_is_branch_open_no_hours_set_always_open_when_active():
    branch = _FakeBranch(is_active=True, opens_at=None, closes_at=None)
    assert branch_hours_service.is_branch_open(branch) is True


def test_is_branch_open_within_normal_window(monkeypatch):
    branch = _FakeBranch(
        opens_at=time.fromisoformat("09:00:00"),
        closes_at=time.fromisoformat("21:00:00"),
    )
    _mock_now(monkeypatch, time.fromisoformat("12:00:00"), weekday=0)
    assert branch_hours_service.is_branch_open(branch) is True


def test_is_branch_open_outside_normal_window(monkeypatch):
    branch = _FakeBranch(
        opens_at=time.fromisoformat("09:00:00"),
        closes_at=time.fromisoformat("21:00:00"),
    )
    _mock_now(monkeypatch, time.fromisoformat("22:00:00"), weekday=0)
    assert branch_hours_service.is_branch_open(branch) is False


def test_is_branch_open_wrong_weekday(monkeypatch):
    branch = _FakeBranch(
        opens_at=time.fromisoformat("09:00:00"),
        closes_at=time.fromisoformat("21:00:00"),
        working_days=[0, 1, 2, 3, 4],  # weekdays only
    )
    _mock_now(monkeypatch, time.fromisoformat("12:00:00"), weekday=5)  # Saturday
    assert branch_hours_service.is_branch_open(branch) is False


def test_is_branch_open_overnight_window_before_midnight(monkeypatch):
    branch = _FakeBranch(
        opens_at=time.fromisoformat("20:00:00"),
        closes_at=time.fromisoformat("04:00:00"),
    )
    _mock_now(monkeypatch, time.fromisoformat("23:00:00"), weekday=0)
    assert branch_hours_service.is_branch_open(branch) is True


def test_is_branch_open_overnight_window_after_midnight(monkeypatch):
    branch = _FakeBranch(
        opens_at=time.fromisoformat("20:00:00"),
        closes_at=time.fromisoformat("04:00:00"),
    )
    _mock_now(monkeypatch, time.fromisoformat("02:00:00"), weekday=0)
    assert branch_hours_service.is_branch_open(branch) is True


def test_is_branch_open_overnight_window_outside_it(monkeypatch):
    branch = _FakeBranch(
        opens_at=time.fromisoformat("20:00:00"),
        closes_at=time.fromisoformat("04:00:00"),
    )
    _mock_now(monkeypatch, time.fromisoformat("12:00:00"), weekday=0)
    assert branch_hours_service.is_branch_open(branch) is False


# --- PATCH /branches/{id}/hours -----------------------------------------


def test_update_hours_requires_authentication(client, branch_and_item):
    branch, _item = branch_and_item
    resp = client.patch(f"/api/v1/branches/{branch['id']}/hours", json=ALL_DAY_HOURS)
    assert resp.status_code == 401  # no Authorization header at all


def test_update_hours_rejects_non_staff(client, branch_and_item, supplier2_token):
    branch, _item = branch_and_item
    resp = client.patch(
        f"/api/v1/branches/{branch['id']}/hours",
        json=ALL_DAY_HOURS,
        headers=_auth_headers(supplier2_token),
    )
    assert resp.status_code == 403


def test_update_hours_allows_owner(client, branch_and_item, supplier_token):
    branch, _item = branch_and_item
    resp = client.patch(
        f"/api/v1/branches/{branch['id']}/hours",
        json=ALL_DAY_HOURS,
        headers=_auth_headers(supplier_token),
    )
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert body["opens_at"] == "00:00:00"
    assert body["closes_at"] == "23:59:59"


def test_update_hours_allows_admin(client, branch_and_item, admin_token):
    branch, _item = branch_and_item
    resp = client.patch(
        f"/api/v1/branches/{branch['id']}/hours",
        json=ALL_DAY_HOURS,
        headers=_auth_headers(admin_token),
    )
    assert resp.status_code == 200, resp.text


def test_update_hours_is_partial(client, branch_and_item, supplier_token):
    branch, _item = branch_and_item
    client.patch(
        f"/api/v1/branches/{branch['id']}/hours",
        json=ALL_DAY_HOURS,
        headers=_auth_headers(supplier_token),
    )
    resp = client.patch(
        f"/api/v1/branches/{branch['id']}/hours",
        json={"working_days": [0, 1, 2]},
        headers=_auth_headers(supplier_token),
    )
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert body["working_days"] == [0, 1, 2]
    assert body["opens_at"] == "00:00:00"  # untouched by the working_days-only patch


def test_update_hours_can_clear_back_to_unrestricted(
    client, branch_and_item, supplier_token
):
    branch, _item = branch_and_item
    client.patch(
        f"/api/v1/branches/{branch['id']}/hours",
        json=ALL_DAY_HOURS,
        headers=_auth_headers(supplier_token),
    )
    resp = client.patch(
        f"/api/v1/branches/{branch['id']}/hours",
        json={"opens_at": None, "closes_at": None},
        headers=_auth_headers(supplier_token),
    )
    assert resp.status_code == 200, resp.text
    assert resp.json()["opens_at"] is None
    assert resp.json()["closes_at"] is None


def test_update_hours_rejects_empty_working_days(
    client, branch_and_item, supplier_token
):
    branch, _item = branch_and_item
    resp = client.patch(
        f"/api/v1/branches/{branch['id']}/hours",
        json={"working_days": []},
        headers=_auth_headers(supplier_token),
    )
    assert resp.status_code == 422


def test_update_hours_rejects_invalid_weekday(client, branch_and_item, supplier_token):
    branch, _item = branch_and_item
    resp = client.patch(
        f"/api/v1/branches/{branch['id']}/hours",
        json={"working_days": [0, 7]},
        headers=_auth_headers(supplier_token),
    )
    assert resp.status_code == 422


def test_update_hours_rejects_duplicate_weekday(
    client, branch_and_item, supplier_token
):
    branch, _item = branch_and_item
    resp = client.patch(
        f"/api/v1/branches/{branch['id']}/hours",
        json={"working_days": [0, 0]},
        headers=_auth_headers(supplier_token),
    )
    assert resp.status_code == 422


# --- is_open_now surfaced on branch reads --------------------------------


def test_branch_defaults_to_open_with_no_hours_set(
    client, branch_and_item, customer_token
):
    branch, _item = branch_and_item
    resp = client.get(
        f"/api/v1/branches/{branch['id']}", headers=_auth_headers(customer_token)
    )
    assert resp.status_code == 200, resp.text
    assert resp.json()["is_open_now"] is True


def test_branch_is_closed_when_is_active_false(
    client, db_session, branch_and_item, supplier_token, customer_token
):
    from app.models.branch import Branch as BranchModel

    branch, _item = branch_and_item
    client.patch(
        f"/api/v1/branches/{branch['id']}/hours",
        json=ALL_DAY_HOURS,
        headers=_auth_headers(supplier_token),
    )
    resp = client.get(
        f"/api/v1/branches/{branch['id']}", headers=_auth_headers(customer_token)
    )
    assert resp.json()["is_open_now"] is True  # sanity: hours alone don't close it

    # No endpoint flips is_active off directly for a branch — go
    # straight to the DB, same as other tests in this project do for
    # state no endpoint exposes a shortcut for.
    db_branch = (
        db_session.query(BranchModel)
        .filter(BranchModel.id == uuid.UUID(branch["id"]))
        .first()
    )
    db_branch.is_active = False
    db_session.commit()

    # A customer can no longer see an inactive branch at all (404, same
    # as before this feature existed) — check via the owner, who
    # always sees their own branch regardless of is_active.
    resp = client.get(
        f"/api/v1/branches/{branch['id']}", headers=_auth_headers(supplier_token)
    )
    assert resp.json()["is_open_now"] is False


def test_cart_blocks_adding_item_when_branch_closed_by_weekday(
    client, db_session, branch_and_item, supplier_token, customer_token
):
    """Deterministic "closed" without any time-of-day dependency:
    working_days excludes today entirely."""
    from app.models.branch import Branch as BranchModel

    branch, item = branch_and_item
    today = _addis_weekday_now()
    other_days = [d for d in range(7) if d != today]
    client.patch(
        f"/api/v1/branches/{branch['id']}/hours",
        json={**ALL_DAY_HOURS, "working_days": other_days},
        headers=_auth_headers(supplier_token),
    )

    resp = client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 1},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 409
    assert "closed" in resp.json()["detail"].lower()

    # Sanity: the branch really is marked closed right now in the DB.
    db_branch = (
        db_session.query(BranchModel)
        .filter(BranchModel.id == uuid.UUID(branch["id"]))
        .first()
    )
    from app.services.branch_hours import is_branch_open

    assert is_branch_open(db_branch) is False


def test_cart_allows_adding_item_when_branch_open_all_day(
    client, branch_and_item, supplier_token, customer_token
):
    branch, item = branch_and_item
    client.patch(
        f"/api/v1/branches/{branch['id']}/hours",
        json=ALL_DAY_HOURS,
        headers=_auth_headers(supplier_token),
    )

    resp = client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 1},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 200, resp.text


def test_checkout_blocks_when_branch_closed_by_weekday(
    client, branch_and_item, supplier_token, customer_token
):
    branch, item = branch_and_item
    client.post(
        "/api/v1/cart/items",
        json={"menu_item_id": item["id"], "quantity": 1},
        headers=_auth_headers(customer_token),
    )

    today = _addis_weekday_now()
    other_days = [d for d in range(7) if d != today]
    client.patch(
        f"/api/v1/branches/{branch['id']}/hours",
        json={**ALL_DAY_HOURS, "working_days": other_days},
        headers=_auth_headers(supplier_token),
    )

    resp = client.post(
        "/api/v1/orders/checkout",
        json={"delivery_mode": "takeaway", "payment_method": "cash"},
        headers=_auth_headers(customer_token),
    )
    assert resp.status_code == 409
    assert "closed" in resp.json()["detail"].lower()
