"""CRM linking for retail locations."""
from __future__ import annotations

from typing import Any, Optional

from app.db import execute, execute_returning, fetch_all, fetch_one


def link_client_to_store(
    supermarket_id: int,
    client_id: int,
    deal_id: Optional[int] = None,
    relationship_type: str = "prospect",
    partnership_status: Optional[str] = None,
    notes: Optional[str] = None,
) -> dict[str, Any]:
    store = fetch_one("SELECT id FROM supermarkets WHERE id = %s", (supermarket_id,))
    client = fetch_one("SELECT id, name FROM clients WHERE id = %s", (client_id,))
    if not store or not client:
        raise ValueError("Store or client not found")

    row = execute_returning(
        """
        INSERT INTO client_supermarket_links (client_id, supermarket_id, deal_id, relationship_type, notes)
        VALUES (%s, %s, %s, %s, %s)
        ON CONFLICT (client_id, supermarket_id) DO UPDATE SET
            deal_id = COALESCE(EXCLUDED.deal_id, client_supermarket_links.deal_id),
            relationship_type = EXCLUDED.relationship_type,
            notes = COALESCE(EXCLUDED.notes, client_supermarket_links.notes)
        RETURNING *
        """,
        (client_id, supermarket_id, deal_id, relationship_type, notes),
    )
    if partnership_status:
        execute(
            """UPDATE supermarkets SET client_id = %s, deal_id = %s,
               partnership_status = %s, last_updated = NOW() WHERE id = %s""",
            (client_id, deal_id, partnership_status, supermarket_id),
        )
    return dict(row or {})


def unlink_client_from_store(supermarket_id: int, client_id: int) -> bool:
    n = execute(
        "DELETE FROM client_supermarket_links WHERE supermarket_id = %s AND client_id = %s",
        (supermarket_id, client_id),
    )
    execute(
        """UPDATE supermarkets SET client_id = NULL, deal_id = NULL,
           partnership_status = 'none', last_updated = NOW()
           WHERE id = %s AND client_id = %s""",
        (supermarket_id, client_id),
    )
    return n > 0


def get_store_crm_context(supermarket_id: int) -> dict[str, Any]:
    links = fetch_all(
        """
        SELECT l.*, c.name AS client_name, c.email AS client_email, c.contact AS client_contact,
               c.stage AS client_stage, d.title AS deal_title, d.value AS deal_value, d.stage AS deal_stage
        FROM client_supermarket_links l
        JOIN clients c ON c.id = l.client_id
        LEFT JOIN deals d ON d.id = l.deal_id
        WHERE l.supermarket_id = %s
        ORDER BY l.created_at DESC
        """,
        (supermarket_id,),
    )
    contacts = fetch_all(
        "SELECT * FROM supermarket_contacts WHERE supermarket_id = %s ORDER BY confidence DESC",
        (supermarket_id,),
    )
    profile = fetch_one("SELECT * FROM supermarket_profiles WHERE supermarket_id = %s", (supermarket_id,))
    halal = fetch_all(
        "SELECT * FROM halal_certifications WHERE supermarket_id = %s ORDER BY matched_confidence DESC",
        (supermarket_id,),
    )
    return {
        "links": [dict(x) for x in links],
        "contacts": [dict(x) for x in contacts],
        "profile": dict(profile) if profile else None,
        "halal_certifications": [dict(x) for x in halal],
    }


def list_crm_options() -> dict[str, Any]:
    clients = fetch_all(
        "SELECT id, name, contact, email, stage, sector FROM clients ORDER BY name LIMIT 500"
    )
    deals = fetch_all(
        """SELECT d.id, d.title, d.value, d.stage, d.client_id, c.name AS client_name
           FROM deals d LEFT JOIN clients c ON c.id = d.client_id
           WHERE d.stage NOT IN ('won','lost') ORDER BY d.updated_at DESC LIMIT 200"""
    )
    return {"clients": [dict(c) for c in clients], "deals": [dict(d) for d in deals]}


def get_client_retail_links(client_id: int) -> list[dict[str, Any]]:
    rows = fetch_all(
        """
        SELECT s.id, s.name, s.chain, s.city, s.province, s.postcode, s.phone, s.email,
               s.partnership_status, s.halal_certified, s.has_halal_section, s.manager_name,
               l.relationship_type, l.notes AS link_notes, l.deal_id, l.created_at AS linked_at
        FROM client_supermarket_links l
        JOIN supermarkets s ON s.id = l.supermarket_id
        WHERE l.client_id = %s
        ORDER BY s.chain, s.city, s.name
        """,
        (client_id,),
    )
    direct = fetch_all(
        """
        SELECT s.id, s.name, s.chain, s.city, s.province, s.postcode, s.phone, s.email,
               s.partnership_status, s.halal_certified, s.has_halal_section, s.manager_name,
               'direct' AS relationship_type, NULL AS link_notes, s.deal_id, s.last_updated AS linked_at
        FROM supermarkets s
        WHERE s.client_id = %s
          AND NOT EXISTS (
              SELECT 1 FROM client_supermarket_links l
              WHERE l.supermarket_id = s.id AND l.client_id = s.client_id
          )
        ORDER BY s.chain, s.city, s.name
        """,
        (client_id,),
    )
    merged: dict[int, dict[str, Any]] = {}
    for row in list(rows) + list(direct):
        merged[int(row["id"])] = dict(row)
    return list(merged.values())
