# -*- coding: utf-8 -*-
from odoo import api, fields, models, _
from odoo.exceptions import UserError


class JbMarkInvoicedWizard(models.TransientModel):
    _name = 'jb.mark.invoiced.wizard'
    _description = 'Mark Timesheet Lines as Invoiced'

    line_ids = fields.Many2many(
        comodel_name='account.analytic.line',
        relation='jb_mark_invoiced_wizard_line_rel',
        column1='wizard_id',
        column2='line_id',
        string='Timesheet Lines',
        help='Timesheet lines to mark as invoiced.',
    )
    invoiced_date = fields.Date(
        string='Invoiced Date',
        required=True,
        default=fields.Date.today,
        help='Date to record as the invoiced date on selected lines.',
    )

    # ------------------------------------------------------------------
    # Default: pre-populate from active_ids context
    # ------------------------------------------------------------------

    @api.model
    def default_get(self, fields_list):
        res = super().default_get(fields_list)
        active_ids = self.env.context.get('active_ids', [])
        if active_ids and 'line_ids' in fields_list:
            res['line_ids'] = [(6, 0, active_ids)]
        return res

    # ------------------------------------------------------------------
    # Actions
    # ------------------------------------------------------------------

    def action_mark_invoiced(self):
        """Mark all selected timesheet lines as invoiced."""
        self.ensure_one()
        if not self.line_ids:
            raise UserError(_('No timesheet lines selected.'))

        self.line_ids.write({
            'is_invoiced': True,
            'invoiced_date': self.invoiced_date,
        })

        return {'type': 'ir.actions.act_window_close'}

    @api.model
    def action_open_wizard(self):
        """Open the Mark Invoiced wizard (called from server action)."""
        wizard = self.create({})
        return {
            'type': 'ir.actions.act_window',
            'name': _('Mark as Invoiced'),
            'res_model': 'jb.mark.invoiced.wizard',
            'view_mode': 'form',
            'res_id': wizard.id,
            'target': 'new',
        }
