# -*- coding: utf-8 -*-
"""
Modelos para cachear datos de WACRM (Supabase) en Odoo.
Permiten al frontend mostrar mensajes y leads sincronizados con WACRM.
"""

from odoo import models, fields, api
from odoo.exceptions import UserError
import requests
import json
import logging

_logger = logging.getLogger(__name__)


class SkeenWacrmContact(models.Model):
    _name = 'skeen.wacrm.contact'
    _description = 'Contacto WACRM'
    _order = 'updated_at desc'

    external_id = fields.Char('ID WACRM', required=True, index=True)
    account_id = fields.Char('Account ID')
    phone = fields.Char('Teléfono', index=True)
    name = fields.Char('Nombre')
    email = fields.Char('Correo')
    company = fields.Char('Compañía')
    avatar_url = fields.Char('Avatar URL')
    source = fields.Char('Origen')
    created_at = fields.Datetime('Creado en WACRM')
    updated_at = fields.Datetime('Actualizado en WACRM')

    conversation_ids = fields.One2many('skeen.wacrm.conversation', 'contact_id', string='Conversaciones')
    deal_ids = fields.One2many('skeen.wacrm.deal', 'contact_id', string='Deals')


class SkeenWacrmConversation(models.Model):
    _name = 'skeen.wacrm.conversation'
    _description = 'Conversación WACRM'
    _order = 'last_message_at desc'

    external_id = fields.Char('ID WACRM', required=True, index=True)
    contact_id = fields.Many2one('skeen.wacrm.contact', string='Contacto', index=True, ondelete='cascade')
    contact_phone = fields.Char(related='contact_id.phone', string='Teléfono', store=True)
    contact_name = fields.Char(related='contact_id.name', string='Nombre', store=True)
    status = fields.Selection([
        ('open', 'Abierta'),
        ('pending', 'Pendiente'),
        ('closed', 'Cerrada'),
    ], string='Estado', default='open')
    assigned_agent = fields.Char('Agente asignado')
    assigned_agent_id = fields.Char('ID Agente WACRM')
    last_message_text = fields.Text('Texto del último mensaje')
    last_message_at = fields.Datetime('Último mensaje')
    unread_count = fields.Integer('No leídos', default=0)
    created_at = fields.Datetime('Creado en WACRM')
    updated_at = fields.Datetime('Actualizado en WACRM')

    message_ids = fields.One2many('skeen.wacrm.message', 'conversation_id', string='Mensajes')


class SkeenWacrmMessage(models.Model):
    _name = 'skeen.wacrm.message'
    _description = 'Mensaje WACRM'
    _order = 'created_at desc'

    external_id = fields.Char('ID WACRM', required=True, index=True)
    conversation_id = fields.Many2one('skeen.wacrm.conversation', string='Conversación', index=True, ondelete='cascade')
    contact_id = fields.Many2one(related='conversation_id.contact_id', string='Contacto', store=True)
    sender_type = fields.Selection([
        ('customer', 'Cliente'),
        ('agent', 'Agente'),
        ('bot', 'Bot'),
    ], string='Remitente', required=True)
    content_type = fields.Selection([
        ('text', 'Texto'),
        ('image', 'Imagen'),
        ('document', 'Documento'),
        ('audio', 'Audio'),
        ('video', 'Video'),
        ('location', 'Ubicación'),
        ('template', 'Plantilla'),
        ('interactive', 'Interactivo'),
    ], string='Tipo de contenido', default='text')
    content_text = fields.Text('Contenido')
    media_url = fields.Char('URL de medio')
    template_name = fields.Char('Nombre de plantilla')
    status = fields.Selection([
        ('sending', 'Enviando'),
        ('sent', 'Enviado'),
        ('delivered', 'Entregado'),
        ('read', 'Leído'),
        ('failed', 'Fallido'),
    ], string='Estado', default='sent')
    created_at = fields.Datetime('Creado en WACRM')


class SkeenWacrmPipeline(models.Model):
    _name = 'skeen.wacrm.pipeline'
    _description = 'Pipeline WACRM'

    external_id = fields.Char('ID WACRM', required=True, index=True)
    name = fields.Char('Nombre', required=True)
    created_at = fields.Datetime('Creado en WACRM')


class SkeenWacrmStage(models.Model):
    _name = 'skeen.wacrm.stage'
    _description = 'Etapa de Pipeline WACRM'

    external_id = fields.Char('ID WACRM', required=True, index=True)
    pipeline_id = fields.Many2one('skeen.wacrm.pipeline', string='Pipeline', index=True, ondelete='cascade')
    name = fields.Char('Nombre', required=True)
    position = fields.Integer('Posición', default=0)
    color = fields.Char('Color', default='#3b82f6')


class SkeenWacrmDeal(models.Model):
    _name = 'skeen.wacrm.deal'
    _description = 'Deal / Lead WACRM'
    _order = 'created_at desc'

    external_id = fields.Char('ID WACRM', required=True, index=True)
    title = fields.Char('Título', required=True)
    contact_id = fields.Many2one('skeen.wacrm.contact', string='Contacto', index=True)
    contact_name = fields.Char(related='contact_id.name', string='Nombre contacto', store=True)
    contact_phone = fields.Char(related='contact_id.phone', string='Teléfono contacto', store=True)
    conversation_id = fields.Char('ID Conversación WACRM')
    pipeline_id = fields.Many2one('skeen.wacrm.pipeline', string='Pipeline')
    stage_id = fields.Many2one('skeen.wacrm.stage', string='Etapa')
    value = fields.Float('Valor', default=0.0)
    currency = fields.Char('Moneda', default='USD')
    status = fields.Selection([
        ('open', 'Abierto'),
        ('won', 'Ganado'),
        ('lost', 'Perdido'),
    ], string='Estado', default='open')
    expected_close_date = fields.Date('Cierre esperado')
    notes = fields.Text('Notas')
    assigned_to = fields.Char('Asignado a')
    partner_id = fields.Many2one('res.partner', string='Paciente', index=True,
                                 help='Paciente SKEEN ligado al convertir el lead')
    created_at = fields.Datetime('Creado en WACRM')
    updated_at = fields.Datetime('Actualizado en WACRM')
